Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DLR, Datatype inference with Dynamic keyword

Just Asking :

Why 'withOffset' variable is inferred as dynamic as Parse method returns Struct ?

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

and after explicit cast its back to Struct?

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

since the return type of DateTimeOffset.Parse is DateTimeOffset, and the compiler must know that. keeping that in mind, what ever method it invoke at runtime, the return is always DateTimeOffset.

The specs tells

Since your method takes dynamic as an argument, it qualifies for "dynamic binding"

bit fishy.

What's point in having such specification? OR in which circumstance DateTimeOffset.Parse will not return STRUCT ( forgetting DLR for moment.. )?

Compiler need to be clever, if all methods/overload in the class have same return type to gain performance benefit in long run.

like image 288
codeSetter Avatar asked Nov 22 '13 17:11

codeSetter


1 Answers

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.


this is because in below line str is dynamic

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

At compile time str is dynamic, the type of str get to know at runtime only that is the reason compiler treat withOffset as dynamic


its known to you that str is get converted to datetime structure but for compiler that it get to know only at runtime...

like image 183
Pranay Rana Avatar answered Sep 29 '22 23:09

Pranay Rana