65.9K
CodeProject is changing. Read more.
Home

Misconception of Dynamic Type Passed to Function and Type Returned

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jan 28, 2014

CPOL

1 min read

viewsIcon

5106

Here is a misconception of dynamic type passed to function and type returned

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

Check the below code:

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

According to written code, most developers think 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 compiler treats "var withOffset" as DateTimeOffset and all the method / property is available which is available for "DateTimeOffset" type is available for "withOffset" variable. But it's not true.

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

The 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