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.
Instantiate a new human-list that takes the joes as input:
List<human> humanJoes = new List<human>(joes);
No. The co/contravariance features of C# 4.0 only support interfaces and delegates. The do not support concrete types like List<T>
.