473,785 Members | 2,488 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

difference between List<object> and List<MyClass>

Hi

I seem to have a bit of trouble understanding one bit of how generics work:

In C#, every class automatically derives from object, and inherits a bunch
of properties (i.e. ToString()). Thus,

(MyClass is object) should always evaluate as true.

However, if I have a method with the following signature:

private void myMethod(List<o bjectinput)

And I try to call it

myMethod(new List<MyClass>() )

the compiler complains that it cannot convert from
System.Collecti ons.Generic.Lis t<MyNamespace.M yClassto
System.Collecti ons.Generic.Lis t<object>. And if I try to cast List<MyClass>
to List<objectthat doesn't work either.

Likewise

List<objectmyOb js = new List<object>();
myObjs.AddRange (new List<MyClass>() );

fails with the same error. However, if I I fill up myObjs as follows:

List<objectmyOb js = new List<object>();
List<MyClassmyC lasses = new List<MyClass>() ;
foreach (MyClass c in myClasses)
{
myObjs.Add((obj ect)c);
}

then it works. Even if I leave away the cast to object in the line
myObjs.Add(..) it works (as is to be expected since MyClass is an object.

Since ever class derives from object, why do the the first two examples not
work? Does class inheritance not translate into generics inheritance?

Regards
Stephan
Jul 25 '07 #1
9 6999
just because MyClass : object, it does not follow that List<MyClass:
List<object>

What you need is:

private void myMethod<T>(Lis t<Tinput) {}

you can now use
List<MyClassdat a = blah;
myMethod(data); // note the compiler infers T

Marc

Jul 25 '07 #2
On Jul 25, 11:08 am, "Stephan Steiner" <stephan.stei.. .@nextiraone.ch >
wrote:

<snip>
Since ever class derives from object, why do the the first two examples not
work? Does class inheritance not translate into generics inheritance?
It doesn't translate into type parameter inheritance. Or rather,
generic types aren't covariant in their type parameters, to use the
jargon :)

In short, a List<stringisn' t a List<object>. This actually adds to
type safety - because one of the things you can do with a List<object>
is add *any* object to it, whereas you can't do that with a
List<string(you can only add strings).

Suppose the following were valid:
List<stringstri ngs = new List<string>();
List<objectobje cts = strings;
objects.Add(new object());

The first and third lines are definitely valid - so the only chance
for catching the problem at compile time is for the second line to be
invalid.

Suppose it's valid though - what would you expect to happen? Either it
should blow up at runtime, or the list of strings contains a non-
string. One of the ideas of generics is to push type safety to
compilation time rather than runtime - hence the error.

Jon

Jul 25 '07 #3
One of the ideas of generics is to push type safety to
compilation time rather than runtime - hence the error.
Just to tie the two posts together, Jon's explanation neatly
covers *why* the "myMethod<T>(Li st<Tinput)" trick works -
inside myMethod, you can now (as an example) add any item
to "input", *as long as* it is castable to T. So:

input.Add(new object());

would fail at compile time, but:

input.Add(new T());

would be fine, given a suitable constructor condition on T:

void myMethod<T>(Lis t<Tinput) where T : new() {}

If you want to allow lists of some class / interface (e.g. to
use properties / methods of such), then the "obvious" (but
wrong) waty to do this is:

myMethod(List<I SomeInterfacein put) {} // not ideal; very restrictire

this is better expressed via a condition:

void myMethod<T>(Lis t<Tinput) where T : ISomeInterface {}

or if you want to allow arrays, collections, etc to be passed in:

void myMethod<T>(ILi st<Tinput) where T : ISomeInterface {}

Marc

Jul 25 '07 #4
In article <11************ **********@22g2 000hsm.googlegr oups.com>,
ma**********@gm ail.com says...
void myMethod<T>(Lis t<Tinput) where T : ISomeInterface {}

or if you want to allow arrays, collections, etc to be passed in:

void myMethod<T>(ILi st<Tinput) where T : ISomeInterface {}
Did you mean IEnumerable<Tin stead of IList<T>? You cannot pass an
array when input parameter is declared as IList<T>. You can pass both
arrays and lists if input was defined as IEnumerable<T>.

--
Marcin Hoppe (marcin.hoppe at gmail.com)
Jul 25 '07 #5
Did you mean IEnumerable<Tin stead of IList<T>?

I meant IList<T>
You cannot pass an array when input parameter is declared as IList<T>.
Yes you can (working example below). Add() etc will obviously throw an
exception (presumably NotSupported... or InvalidOperatio n...), but
many of the IList<Tfunction s will work fine, such as enumeration,
length query and indexer access - all perfectly type safe.

Marc

using System;
using System.Collecti ons.Generic;
using System.Diagnost ics;

static class Program {
static void Main() {
int[] data = { 1, 3, 5 };
Test(data);
}
static void Test<T>(IList<T list) {
foreach (T item in list) {
Debug.WriteLine (item);
}
}
}

Jul 25 '07 #6
Not sure if my last post went out, but yes I meant IList<T>, and yes
it works just fine. Add() isn't supported, but you can check the
length, enumerate, use the indexer, etc.

Marc

Jul 25 '07 #7
In article <11************ **********@19g2 000hsx.googlegr oups.com>,
ma**********@gm ail.com says...
Not sure if my last post went out, but yes I meant IList<T>, and yes
it works just fine. Add() isn't supported, but you can check the
length, enumerate, use the indexer, etc.
I wasn't aware of that. MSDN says that both in C# 1.2 and 2.0 a single
dimensional array implements IList (or IList<T>).

Interesting thing is the way method IList.Clear works. It sets all the
elements of the array either to 0, false or null, whichever is
appropriate. The IList<T>.Clear, however, throws an exception.

Thanks for a good point!

--
Marcin Hoppe (marcin.hoppe at gmail.com)
Jul 26 '07 #8
Interesting thing is the way method IList.Clear works. It sets all the
elements of the array either to 0, false or null, whichever is
appropriate. The IList<T>.Clear, however, throws an exception.
Interesting; I didn't know that...

Personally, I think the exception (IList<T>) is the correct
implementation; if
all you have is a list, you expect Clear() to remove the elements.
Since you
can't remove from an array, it makes sense to throw. I guess the IList
approach was somebody trying to be clever, and ignoring the meaning
from
the contract:

IList.Clear Method ... Removes all items from the IList.
(http://msdn2.microsoft.com/en-us/library/
system.collecti ons.ilist.clear .aspx)

Marc

Jul 26 '07 #9
In article <11************ **********@22g2 000hsm.googlegr oups.com>,
ma**********@gm ail.com says...
Interesting; I didn't know that...

Personally, I think the exception (IList<T>) is the correct
implementation; if
all you have is a list, you expect Clear() to remove the elements.
Since you
can't remove from an array, it makes sense to throw. I guess the IList
approach was somebody trying to be clever, and ignoring the meaning
from
the contract:

IList.Clear Method ... Removes all items from the IList.
(http://msdn2.microsoft.com/en-us/library/
system.collecti ons.ilist.clear .aspx)
Yup. I also think than an exception would be the preferred way to go.

--
Marcin Hoppe (marcin.hoppe at gmail.com)
Jul 26 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2818
by: GRiN | last post by:
In VS2003 I have been using an ArrayList loading it with a copy constructor and it seems to work fine. {I am acutally loading a lot of constants first, not one a shown} public ArrayList al; .... MyClass mc = new MyClass() mc.a = 1; loop... {
5
2007
by: Gary | last post by:
I am using List<MyClassto store a bunch of MyClasses. And in my program, I want to change the content of one class in this list. However, it seems to me that this list keeps an original copy and is only "readable". Following is my code: int index = GetMyClassIndFromName(string); if (index != -1) {
0
2441
by: adebaene | last post by:
Hello all, Has everyone tried to use the functions taking a Predicate in Generics container in C++/CLI? Say I have a List<MyClass^>^ my_array, and I want to call RemoveAll on it. How would you do this? The most natural approach would be :
2
1479
by: Jamie Risk | last post by:
As an example supposing I have an object: public class myClass { public List<bytelistOfBytes; public int X; public int Y; } and a method ("op()") whose signature is:
5
640
by: Stephan Steiner | last post by:
Hi I seem to have a bit of trouble understanding one bit of how generics work: In C#, every class automatically derives from object, and inherits a bunch of properties (i.e. ToString()). Thus, (MyClass is object) should always evaluate as true. However, if I have a method with the following signature:
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10091
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.