I have the following setup and it seems that my object cannot be converted to the generic type. While it is actually the base class. Why doesn’t this work? It seems so logical to me.
public class AList<T> where T : A
{
void DoStuff(T foo)
{
}
void CallDoStuff()
{
DoStuff(new A()); // ERROR: Cannot convert A to T
}
}
public class A
{
}
The problem here is that the constraint says that
Tmust beAor a class derived fromA.Now, when you instantiate
AListwith a concrete type,Tis a very specific class. And if you didn’t instantiateAListwithAitself but with a subclass of it,Tis a subclass ofA.You can’t convert an instance with a runtime type of the base class to one of its subclasses, as it misses all the information that is being added by the subclass.
Example:
Would you expect that code to work? Surely not, because a
Catis also aAnimalbut aAnimalis not aCat.If you would expect the above code to actually work, ask yourself what is supposed to happen when the following code is executed:
d.Bar = 42;Animaldoesn’t contain a definition forBar.The same is happening in your code – it’s just a little bit more obscured with the generics in the game.