interface Base { ... }
class Sub : Base { ... }
class OtherBase<T> where T : Base { ... }
class OtherSub<T> : OtherBase<T> where T : Base { ... }
//...in some class
void Call<T>() where T : OtherBase<Base> { }
//...
Call<OtherSub<Sub>>(); //compile fails...
Seems like when using generics, the compiler won’t cast a inner generic type (Base/Sub) in the
generic type (OtherBase/OtherSub). Why does this happen?
Update:
Please also explain the difference between the above and the following (which works)
void Call<T>() where T : Base { }
//...
Call<Sub>();
Forbidding this behaviour (known as “generic variance”) is necessary because otherwise the following code would compile:
We’ve added a number to a list of strings. Not good. (Incidentally, the code would compile for arrays instead of
Lists because Java allowed this for some reason; however, this will raise a runtime exception.)You can avoid this in your case though:
And call it like this:
C# 4.0 furthermore provides generic variance for interfaces. However, their use isn’t often necessary.