Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need new keywords for Covariance and Contravariance in C#?

Can someone explain why there is the need to add an out or in parameter to indicate that a generic type is Co or Contra variant in C# 4.0?

I've been trying to understand why this is important and why the compiler can't just figure it out..

Thanks,

Josh

like image 303
JoshBerke Avatar asked Nov 06 '08 14:11

JoshBerke


People also ask

Why is covariance and contravariance important?

In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.

What is the difference between covariance and contravariance in delegates?

Covariance permits a method to have return type that is more derived than that defined in the delegate. Contravariance permits a method that has parameter types that are less derived than those in the delegate type.

Why is contravariance useful?

This is mainly useful when using already defined standard interfaces. Covariance means that you can use IEnumerable<string> in place where IEnumerable<object> is expected. Contravariance allows you to pass IComparable<object> as an argument of a method taking IComparable<string> .

What is covariance in programming?

Covariance means that a method can return a type that is derived from the delegate's return type. Contra-variance means that a method can take a parameter that is a base of the delegate's parameter type.

How do you declare a generic interface as Contravariant?

You can declare a generic type parameter contravariant by using the in keyword. The contravariant type can be used only as a type of method arguments and not as a return type of interface methods. The contravariant type can also be used for generic constraints.


2 Answers

Eric Lippert, who works on the langauge, has a series of posts on msdn that should help clarify the issues involved:
http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

When reading the articles shown at that link, start at the bottom and work up.

Eventually you'll get to #7 (Why do we need a syntax at all?).

like image 77
Joel Coehoorn Avatar answered Sep 22 '22 23:09

Joel Coehoorn


We don't actually need them, any more then we need abstract on classes or both out and ref. They exist just so that we, as programmers, can make our intention crystal clear, so that maintenance programmer know what we are doing, and the compiler can verify that we are doing it right.

like image 42
James Curran Avatar answered Sep 26 '22 23:09

James Curran