LiverpoolsNumber9
LiverpoolsNumber9

Reputation: 2394

Cast collection of generic type to collection of non-generic type in C#

Given this type:

public class DataRow
{

}
public class DataRow<T> : DataRow
{

}

And this use of it:

public class DataRowCollection
{
    public IList<DataRow> List{get;set;}
}
public class DataRowCollection<T> : DataRowCollection
{
    public new IList<DataRow<T>> List{get;set;}
}

Why can't I assign base.List to this.List in DataRowCollection<T> ? And why can't I cast this.List to the non-generic type and assign to base.List ?

Edit: the code that is failing in DataRowCollection<T>

base.List = (IList<DataRow>)this.List;

(The cast fails)

base.List = this.List;

(Compiler error)

Upvotes: 1

Views: 189

Answers (1)

Servy
Servy

Reputation: 203802

Because IList is invariant, and not covariant or contravariant with respect to its generic type.

If that cast were valid then you could add a DataRow<SomeTypeThatIsNotT> to the list, which would be breaking the contract of that IList.

Upvotes: 4

Related Questions