Misconception Related To Dynamic Type Variable In C#

This small article is about the misconception related to the dynamic type variable supported by the C# language. Read more about the dynamic keyword over here: Dynamic Types

Check the mentioned below code

dynamic str = "22/11/2013 10:31:45 +00:01";
var withOffset = DateTimeOffset.Parse(str);

According to the written code, most of the developers thinks after writing the above code type of "withOffset" variable is type written by the function "DateTimeOffset.Parse" i.e. "DateTimeOffset".

Developer of the code thinks that the compiler treats "var withOffset" as the DateTimeOffset and all the available methods / properties, which are  available for the "DateTimeOffset" type is also available for the "withOffset" variable. But its not true.



So the question that rises here is why does the type does not get changed to the return type of the function.

Answer is:

When you use dynamic, the entire expression is treated as a dynamic expression at the compile time, which causes the compiler to treat everything as dynamic and gets the run-time binding.

This is explained in 7.2 of the C# Language specification

When no dynamic expressions are involved, C# defaults to static binding, which means that the compile-time types of constituent expressions are used in the selection process. However, when one of the constituent expressions in the operations, listed above, is a dynamic expression, the operation gets dynamically bound instead.

This means that most of the operations (the types are listed in section 7.2 of the spec) which have any element that is declared as dynamic will be evaluated as dynamic, and the result will be a dynamic.

Since the argument is dynamic, the compiler cannot know which method will be called at the runtime. Therefore, it cannot know what the return type will be. We may know that the return type will be DateTimeOffset, but the compiler does not, and cannot, know that.

Reference

C# DLR, Datatype inference with Dynamic keyword

Download
 
Free book on C# language specification