UserControl
UserControl

Reputation: 15159

Type variance in .NET Framework 4.0

IEnumerable<T>, IComparable<T> and a few more are now type-variant. IList<T>, ICollection<T> and many others aren't. Why?

Upvotes: 6

Views: 577

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062925

See also: What C# 4.0 covariance doesn't do

Upvotes: 2

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422026

.NET Framework 4.0 introduces safe co/contra-variance. IList<T> and ICollection<T> have T both in input and output positions while IEnumerable<T> has T only in output positions and IComparable<T> has T only in input positions.

Assume IList<T> supported type variance:

static void FailingMethod(IList<object> list) {
    list[0] = 5;
}

static void Test() {
    var a = new List<string>();
    a[0] = "hello";
    FailingMethod(a); // if it was variant, this method call would be unsafe
}

Upvotes: 11

Robert Harvey
Robert Harvey

Reputation: 180808

Anders Hejlseberg has a brief, but illuminating discussion that describes co/contravariance in his talk, "The Future of C#." His discussion on covariance and contravariance starts at 50 minutes and 17 seconds into the presentation.

http://channel9.msdn.com/pdc2008/TL16/

Upvotes: 1

Related Questions