Pranay Rana: Misconception of Dyanmic type passed to function and type returned

Saturday, November 23, 2013

Misconception of Dyanmic type passed to function and type returned

Small post is about miconception related to dynamic type variable supported by the C# langauge. Read more about dynamic keyword over here : Dynamic Types

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

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

Devloper of the code thinks that compiler treat "var withOffset" as DateTimeOffset and all the method / property is avaiable which is avaialbe for "DateTimeOffset" type is avaible for "withOffset" variable. But its not true.



So question get raised why the type of not get changed to return type of the function.

Answer is :
When you use dynamic, the entire expression is treated at compile time as a dynamic expression, which causes the compiler to treat everything as dynamic and get 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 is instead dynamically bound.
This basically means that most 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 runtime. Therefore, it cannot know what the return type will be. We might know that the return type will be DateTimeOffset, but the compiler does not, and cannot, know that.
Reference : http://stackoverflow.com/questions/20150687/c-sharp-dlr-datatype-inference-with-dynamic-keyword

No comments:

Post a Comment