Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "dynamic" not covariant and contravariant with respect to all types when used as a generic type parameter?

Tags:

I am wondering if dynamic is semantically equivalent to object when used as a generic type parameter. If so, I am curious why this limitation exists since the two are different when assigning values to variables or formal parameters.

I've written a small experiment in C# 4.0 to tease apart some of the details. I defined some simple interfaces and implementations:

interface ICovariance<out T> { T Method(); }  interface IContravariance<in T> { void Method(T argument); }  class Covariance<T> : ICovariance<T> {     public T Method() { return default(T); } }  class Contravariance<T> : IContravariance<T> {     public void Method(T argument) { } } 

The interesting details of the experiment:

class Variance {     static void Example()     {         ICovariance<object> c1 = new Covariance<string>();         IContravariance<string> c2 = new Contravariance<object>();          ICovariance<dynamic> c3 = new Covariance<string>();         IContravariance<string> c4 = new Contravariance<dynamic>();          ICovariance<object> c5 = new Covariance<dynamic>();         IContravariance<dynamic> c6 = new Contravariance<object>();          // The following statements do not compile.         //ICovariance<string> c7 = new Covariance<dynamic>();         //IContravariance<dynamic> c8 = new Contravariance<string>();          // However, these do.         string s = new Covariance<dynamic>().Method();         new Contravariance<string>().Method((dynamic)s);            } } 

The first two statements with c1 and c2 demonstrate that basic covariance and contravariance are working. I then use c3 and c4 to show that dynamic can be used as a generic type parameter in the same fashion.

The statements with c5 and c6 reveal that a conversion from dynamic to object is always valid. This isn't really too surprising, since object is an ancestor of all other types.

The final experiment with c7 and c8 is where I start to become confused. It implies that methods that return dynamic objects are not substitutes for methods that return string ones, and similarly that methods that accept string objects cannot take dynamic ones. The final two statements with the assignment and method call show this is clearly not the case, hence my confusion.

I thought about this a little, and wondered if this is to prevent programmers from using ICovariance<dynamic> as a stepping stone between type conversions that would result in run-time errors, such as:

ICovariance<dynamic> c9 = new Covariance<Exception>(); ICovariance<string> c10 = c9; // While this is definitely not allowed: ICovariance<string> c11 = new Covariance<Exception>(); 

However, this is unconvincing in the case of dynamic since we lose type-safety anyway:

dynamic v1 = new Exception(); string  v2 = v1; 

Put another way, the question is "Why does the semantics of dynamic differ between assignment and covariance/contravariance with generics?"

like image 321
ide Avatar asked Feb 03 '11 22:02

ide


People also ask

How does a generic method differ from a generic type?

From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.

What is covariance and Contravariance in generics?

Covariance and contravariance are terms that refer to the ability to use a more derived type (more specific) or a less derived type (less specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.

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.

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

I am wondering if dynamic is semantically equivalent to object when used as a generic type parameter.

Your conjecture is completely correct.

"dynamic" as a type is nothing more than "object" with a funny hat on, a hat that says "rather than doing static type checking for this expression of type object, generate code that does the type checking at runtime". In all other respects, dynamic is just object, end of story.

I am curious why this limitation exists since the two are different when assigning values to variables or formal parameters.

Think about it from the compiler's perspective and then from the IL verifier's perspective.

When you're assigning a value to a variable, the compiler basically says "I need to generate code that does an implicit conversion from a value of such and such a type to the exact type of the variable". The compiler generates code that does that, and the IL verifier verifies its correctness.

That is, the compiler generates:

Frob x = (Frob)whatever; 

But limits the conversions to implicit conversions, not explicit conversions.

When the value is dynamic, the compiler basically says "I need to generate code that interrogates this object at runtime, determines its type, starts up the compiler again, and spits out a small chunk of IL that converts whatever this object is to the type of this variable, runs that code, and assigns the result to this variable. And if any of that fails, throw."

That is, the compiler generates the moral equivalent of:

Frob x = MakeMeAConversionFunctionAtRuntime<Frob>((object)whatever); 

The verifier doesn't even blink at that. The verifier sees a method that returns a Frob. That method might throw an exception if it is unable to turn "whatever" into a Frob; either way, nothing but a Frob ever gets written into x.

Now think about your covariance situation. From the CLR's perspective, there is no such thing as "dynamic". Everywhere that you have a type argument that is "dynamic", the compiler simply generates "object" as a type argument. "dynamic" is a C# language feature, not a Common Language Runtime feature. If covariance or contravariance on "object" isn't legal, then it isn't legal on "dynamic" either. There's no IL that the compiler can generate to make the CLR's type system work differently.

This then explains why it is that you observe that there is a conversion from, say, List<dynamic> to and from List<object>; the compiler knows that they are the same type. The specification actually calls out that these two types have an identity conversion between them; they are identical types.

Does that all make sense? You seem very interested in the design principles that underly dynamic; rather than trying to deduce them from first principles and experiments yourself, you could save yourself the bother and read Chris Burrows' blog articles on the subject. He did most of the implementation and a fair amount of the design of the feature.

like image 113
Eric Lippert Avatar answered Oct 02 '22 18:10

Eric Lippert


for this one:

ICovariance<string> c7 = new Covariance<dynamic>(); 

reason is obvious, if it was possible then you could do:

c7.Method().IndexOf(...); 

and it will definitely fail, except if dynamic is not string or has those method.

since (even after all the changes) c# is not dynamic language. Covariance is allowed only when it is definitely safe. You can of course shot into your feet and call IndexOf on dynamic variable, but you can't let users of your API to do it unintentionally. For example if you return such a ICovariance<string> with dynamic undercover calling code might fail!

Remember the rule, D is covariant to B if there is a cast from D to B. In this case there is no cast from dynamic to string.

But dynamic is covariant to object just because everything is derived from it.

like image 23
Andrey Avatar answered Oct 02 '22 17:10

Andrey