Skip to main content

Posts

Showing posts from February, 2014

What's the difference between covariance and assignment compatibility?

"Covariance is the ability to assign an expression of a more specific type to a variable of a less specific type. For example, consider a method M that returns a Giraffe. You can assign the result of M to a variable of type Animal, because Animal is a less specific type that is compatible with Giraffe. Methods in C# are 'covariant' in their return types, which is why when you create a covariant interface, it is indicated with the keyword 'out' -- the returned value comes 'out' of the method." But that's  not at all  what covariance means. That's describing "assignment compatibility" -- the ability to assign a value of a more specific type to a storage of a compatible, less specific type is called "assignment compatibility" because the two types are compatible for the purposes of verifying legality of assignments. So what does covariance mean then? First off, we need to work out precisely what the adjective "

Covariance and Contravariance FAQ

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. The following code demonstrates the difference between assignment compatibility, covariance, and contravariance. // Assignment compatibility.  string  str =  "test" ; // An object of a more derived type is assigned to an object of a less derived type.  object  obj = str; // Covariance.  IEnumerable < string > strings =  new   List < string >(); // An object that is instantiated with a more derived type argument  // is assigned to an object instantiated with a less derived type argument.  // Assignment compatibility is preserved.  IEnumerable < object > objects = strings; // Contravariance.            // Assume that I have this method:  // static void SetObject(object o) { }  Action < object > actObject = SetObject; /