Following snippet wouldn’t compile. With following error:
Cannot implicitly convert type ‘Container<ChildClass>’ to ‘Container<BaseClass>’
class BaseClass {}
class ChildClass : BaseClass {}
class Container<T> where T : BaseClass {}
class Program {
static void Main() {
// why doesn't this work?
Container<BaseClass> obj = new Container<ChildClass>();
}
}
Is this by design? If it is, what is the reason?
(made wiki, in case of dups)
C# (3.0) doesn’t support covariance of lists etc. C# 4.0 will support limited [co|contra]variance, but still not lists.
The problem is that with:
I could do:
which would compile, but not work.
This behaviour is supported for arrays, but largely for historic reasons.