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