Wednesday, July 9, 2014

Covariance and Contravariance in Generics

Covariance

Enables you to use more specific type than the type originally specified.

IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;

Contravariance

Enables you to use more generic type than the type originally specified.

Action<Base> b = (target) => { Console.WriteLine(target.GetType().Name); };
Action<Derived> d = b;
d(new Derived());
Examples from MSDN.


Resources
https://msdn.microsoft.com/en-us/library/ee207183.aspx
http://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook