Tuesday, September 20, 2011

How special var is in C#, var can't be the type of property of class C#

var is static typed - the compiler and runtime know the type - they just save you some typing... the following are 100% identical:
var s = "abc";
string s = "abc";

All that happened was that the compiler figured out that s must be a string (from the initializer). In both cases, it knows (in the IL) that s.Length means the (instance) string.Length property.
dynamic is a very different beast; it is most similar to object, but with dynamic dispatch:
dynamic s = "abc";
Here, s is typed as dynamic. It doesn't know about string.Length, because it doesn't knowanything about s at compile time. For example, the following would compile (but not run) too:
dynamic s = "abc";
At runtime (only), it would check for the FlibbleBananaSnowball property - fail to find it, and explode in a shower of sparks.
With dynamic, properties / methods / operators / etc are resolved at runtime, based on the actualobject. Very handy for talking to COM (which can have runtime-only properties), the DLR, or other dynamic systems, like javascript.

Above are from : 

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.