covariance in c#

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.

Leave a Comment