By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,645 Members | 1,125 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,645 IT Pros & Developers. It's quick & easy.

difference between List<object> and List<MyClass>

P: n/a
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<objectinput)

And I try to call it

myMethod(new List<MyClass>())

the compiler complains that it cannot convert from
System.Collections.Generic.List<MyNamespace.MyClas sto
System.Collections.Generic.List<object>. And if I try to cast List<MyClass>
to List<objectthat doesn't work either.

Likewise

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

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

List<objectmyObjs = new List<object>();
List<MyClassmyClasses = new List<MyClass>();
foreach (MyClass c in myClasses)
{
myObjs.Add((object)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
Share this Question
Share on Google+
9 Replies


P: n/a
just because MyClass : object, it does not follow that List<MyClass:
List<object>

What you need is:

private void myMethod<T>(List<Tinput) {}

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

Marc

Jul 25 '07 #2

P: n/a
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<stringstrings = new List<string>();
List<objectobjects = 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

P: n/a
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>(List<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>(List<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<ISomeInterfaceinput) {} // not ideal; very restrictire

this is better expressed via a condition:

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

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

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

Marc

Jul 25 '07 #4

P: n/a
In article <11**********************@22g2000hsm.googlegroups. com>,
ma**********@gmail.com says...
void myMethod<T>(List<Tinput) where T : ISomeInterface {}

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

void myMethod<T>(IList<Tinput) where T : ISomeInterface {}
Did you mean IEnumerable<Tinstead 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

P: n/a
Did you mean IEnumerable<Tinstead 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 InvalidOperation...), but
many of the IList<Tfunctions will work fine, such as enumeration,
length query and indexer access - all perfectly type safe.

Marc

using System;
using System.Collections.Generic;
using System.Diagnostics;

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

Jul 25 '07 #6

P: n/a
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

P: n/a
In article <11**********************@19g2000hsx.googlegroups. com>,
ma**********@gmail.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

P: n/a
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.collections.ilist.clear.aspx)

Marc

Jul 26 '07 #9

P: n/a
In article <11**********************@22g2000hsm.googlegroups. com>,
ma**********@gmail.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.collections.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 discussion thread is closed

Replies have been disabled for this discussion.