This compiles:
class ReplicatedBaseType
{
}
class NewType: ReplicatedBaseType
{
}
class Document
{
ReplicatedBaseType BaseObject;
Document()
{
BaseObject = new NewType();
}
}
But this does not:
class DalBase<T> : where T: ReplicatedBaseType
{
}
class DocumentTemplate
{
DalBase<ReplicatedBaseType> BaseCollection;
DocumentTemplate ()
{
BaseCollection= new DalBase<NewType>(); // Error in this line. It seems this is not possible
}
}
What’s the reason?
Variance exists in C# 4.0 targetting .NET 4), but is limited to interfaces and usage of
in/out(oh, and arrays of reference-types). For example, to make a covariant sequence:But other than that… no. Stick to either non-generic lists (
IList), or use the expected list type.