Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic vs var in C# [duplicate]

Possible Duplicate:
What’s the difference between dynamic(C# 4) and var?

What is the difference between dynamic and var keyword in .NET 4.0 (VS 2010). As per MSDN, the definition of dynamic is - Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the normal static binding of C# and instead gets resolved dynamically.

Whereas the definition for var is - An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

How is this different in the code context below:

var a1 = new A(); a1.Foo(1);  dynamic a2 = new A(); a2.Foo(1); 
like image 639
Bhaskar Avatar asked Dec 17 '09 10:12

Bhaskar


People also ask

Is var a dynamic type C#?

var is a statically typed variable. It results in a strongly typed variable, in other words the data type of these variables are inferred at compile time. This is done based on the type of value that these variables are initialized with. dynamic are dynamically typed variables.

What does VAR mean in C?

var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.

What is the difference between dynamic type variables and object type variables?

Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime.


2 Answers

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

A a1 = new A(); 

All the binding is still done entirely statically. If you look at the generated code, it will be exactly the same as with the above declaration.

dynamic means that all any expression using a2 is bound at execution time rather than at compile-time, so it can behave dynamically. The compiler won't check whether the Foo method exists - the behaviour is determined at execution time. Indeed, if the object implements IDynamicMetaObjectProvider it could decide what to do with the call at execution time, responding to any method call (or other kind of use) - in other words, there doesn't have to be a "real" method called Foo at all.

If you look at the generated code in the dynamic situation, you'll find all kinds of weird and wonderful stuff going on to do with call sites and binders.

like image 133
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet


var is type safe, in that it uses type inference. Writing var a = new A(); is a shorthand for A a = new A();. A variable which is declared dynamic is NOT type safe and the compiler does nothing to check that the methods you call on it exist.

like image 30
Klaus Byskov Pedersen Avatar answered Sep 28 '22 06:09

Klaus Byskov Pedersen