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.
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:
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 asdynamic
, and the result will be adynamic
.this is because in below line str is dynamic
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...
Here's a really good example of where your assumptions about return type begin to go awry.
As you can see here,
Bar
clearly has an instance methodFoo
that takes a string and returns a string.But now I've created a derived class that also implements
IDynamicMetaObjectProvider
. This is the interface that C# uses to get aDynamicMetaObject
, which determines how the dynamic calls are bound at runtime. For example:This
DynamicMetaObject
overload will capture any calls toFoo
and dynamically redirect them toDynamicFoo
, which has a completely different signature—including that it returnsint
, notstring
.So, if you were to do this...
...the value of
returnValue
at runtime would be1234
, not"Hello, world!"
.Now, in the real world, this is insanely evil. While it's possible to completely rebind functions that are expected to do something in a certain way, doing something ridiculous like this will only serve to confuse people down the road. That being said, it is completely possible in the CLR.
TL;DR: When you're using
dynamic
, you can't always be certain of things you think are correct.