C# 4.0 – Covariance and Contravariance of Generics

Covariance allows casting of generic types to the base types, for example, IEnumerable<X> will be implicitly convertible an IEnumerable<Y> if X can implicitly be converted to Y.

        // List of strings
        IList<string> stringList = new List<string>();

        // We can convert it to an Enumerable collection
        IEnumerable<object> Obj= strings;

For this purpose IEnumerable is marked with the Out modifier.

        public interface IEnumerable<out T> : IEnumerable {
            IEnumerator<T> GetEnumerator();
        }

In C# 4.0, Contravariance allows for example, IComparer<X> to be cast to IComparer<Y> even if Y is a derived type of X. To achieve this IComparer should be marked with the In modifier.

        public interface IComparer<in T> {
            public int Compare(T left, T right);
        }
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!