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<object> input)
And I try to call it
myMethod(new List<MyClass>())
the compiler complains that it cannot convert from
System.Collections.Generic.List<MyNamespace.MyClass> to
System.Collections.Generic.List<object>. And if I try to cast List<MyClass>
to List<object> that doesn't work either.
Likewise
List<object> myObjs = new List<object>();
myObjs.AddRange(new List<MyClass>());
fails with the same error. However, if I I fill up myObjs as follows:
List<object> myObjs = new List<object>();
List<MyClass> myClasses = 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
What you need is:
private void myMethod<T>(List<T> input) {}
you can now use
List<MyClass> data = blah;
myMethod(data); // note the compiler infers T
Marc
<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<string> isn'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<string> strings = new List<string>();
List<object> objects = 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
Just to tie the two posts together, Jon's explanation neatly
covers *why* the "myMethod<T>(List<T> input)" 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<T> input) 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<ISomeInterface> input) {} // not ideal; very restrictire
this is better expressed via a condition:
void myMethod<T>(List<T> input) where T : ISomeInterface {}
or if you want to allow arrays, collections, etc to be passed in:
void myMethod<T>(IList<T> input) where T : ISomeInterface {}
Marc
Did you mean IEnumerable<T> instead 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)
Marc
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!
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
Yup. I also think than an exception would be the preferred way to go.