C# 4.0 is the next version of the C# language being shipped with VS 2010. Personally, I'm still coming to terms with Generics as introduced in C# 2.0 and LINQ which came with 3.0. Anders Hejlsberg touched on the Covariance/Contravariance topic in his TechEd presentation in LA last month entitled "The Future of C#".

Evolution of C# - Anders Hejlsberg

 

The terms Invariance, Covariance and Contravariance are not by any means new. Anyone coming from a computer science background will have encountered the terms. Prior to attending Anders' session, I hadn't given this much conscious thought in a long time - we tend to know what we can and can't do within the syntactical constraints of a language - and tend not to question things further. However, in C# 4.0, delegates and interfaces will play nicer when working with generics. So much attention is likely to be focused on the dynamic programming additions in C# 4.0 (mainly in support of LINQ), that this addition may go unnoticed.

Variance in C# 4.0 - Anders Hejlsberg - Anders Hejlsberg

 

Terminology:

Invariant: A return parameter is invariant if we must use the exact match of the type name. In other words, neither covariance nor contravariance is permitted

Covariant: A parameter is covariant if we can use a more derived type as a substitute for the parameter type. In other words, a subclass instance can be used where a parent class instance was expected.

Contravariant: A return value is contravariant if we can assign the return type to a variable of a less derived type than the parameter. In other words, a super class instance can be used where a subclass instance was expected.

Variance in C# 4.0 - Anders Hejlsberg - Anders Hejlsberg

 

Generally, C# supports covariant parameters and contravariant return types. There has always been support for covariance and contravariance in C# - C# 4.0 will just ensure that generic delegates and interfaces will also behave they way we would expect.

Eric Lippert is the developer responsible for this feature of the C# 4.0 release and has an eleven-part blog series on just this topic. I would also recommend reading Charlie Calvert's article on this topic for some code samples.

Side Note: You do not need VS 2010 to experiment with these features - just download the framework to a test VM.

Tags: , ,

.NET 4.0 | C#