Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

covariance in c#

Is it possible to cast a List<Subclass> to List<Superclass> in C# 4.0?

Something along these lines:

class joe : human {}

List<joe> joes = GetJoes();

List<human> humanJoes = joes;

Isn't this what covariance is for?

if you can do:

human h = joe1 as human;

why shouldn't you be able to do

List<human> humans = joes as List<human>; 

than it wouldn't be legal to do (joe)humans[0] because that item has been down casted.. and everyone would be happy. Now the only alternative is to create a new List

like image 932
Sonic Soul Avatar asked Oct 27 '10 22:10

Sonic Soul


2 Answers

You can't do this, because it wouldn't be safe. Consider:

List<Joe> joes = GetJoes();    
List<Human> humanJoes = joes;
humanJoes.Clear();
humanJoes.Add(new Fred());
Joe joe = joes[0];

Clearly the last line (if not an earlier one) has to fail - as a Fred isn't a Joe. The invariance of List<T> prevents this mistake at compile time instead of execution time.

like image 158
Jon Skeet Avatar answered Oct 28 '22 10:10

Jon Skeet


Instantiate a new human-list that takes the joes as input:

List<human> humanJoes = new List<human>(joes);
like image 24
Paw Baltzersen Avatar answered Oct 28 '22 11:10

Paw Baltzersen