Dynamic vs var

Possible duplicate:
What is the difference between dynamic (C # 4) and var?

What is the difference between the dynamic and var keyword in .NET 4.0 (VS 2010). According to MSDN, the definition of dynamic - dynamic search allows you to write calls to a method, operator and indexer, properties and calls to fields, and even calls to objects that bypass the usual C # static binding and instead solve dynamically.

While the definition for var is: an implicitly typed local variable is strongly typed in the same way as if you declared the type yourself, but the compiler defines the type.

How does this differ in the context of the code below:

var a1 = new A(); a1.Foo(1); dynamic a2 = new A(); a2.Foo(1); 
+49
c # visual-studio-2010
Dec 17 '09 at 10:30
source share
3 answers

var means the static type is inferred - in your case it is exactly equivalent

 A a1 = new A(); 

All bindings are still fully static. If you look at the generated code, it will be exactly the same as with the description above.

dynamic means that any expression using a2 bound at runtime, not at compile time, so it can behave dynamically. The compiler does not check if the Foo method exists - the behavior is determined at runtime. Indeed, if an object implements IDynamicMetaObjectProvider , it can decide what to do with the call at runtime, responding to any method call (or other type of use) - in other words, it is not necessary to be "real", a method called Foo in general.

If you look at the generated code in a dynamic situation, you will find all sorts of strange and wonderful things related to sites and binders.

+88
Dec 17 '09 at 10:35
source share

var is type safe because it uses type inference. The entry var a = new A(); is a shorthand for A a = new A(); . A variable that is declared dynamic is NOT safe, and the compiler does nothing to verify that the methods you call exist.

+24
Dec 17 '09 at 10:35
source share

In the case of var A () must have at compile time the .Foo(int) method.

In the case of dynamic this is not so.

+14
Dec 17 '09 at 10:33
source share



All Articles