.netC#.net

var vs Dynamic in C#

var dynamic
Introduced in C# 3.0 Introduced in C# 4.0
Statically typed – This means the type of variable declared is decided by the compiler at compile time. Dynamically typed – This means the type of variable declared is decided by the compiler at run time.
var type of variables are required to be initialized at the time of declaration or else they encounter the compile time error: Implicitly-typed local variables must be initialized. No need to initialize at the time of declaration.
e.g., var str=”I am a string”; e.g., dynamic str;
Looking at the value assigned to the variable str, the compiler will treat the variable str as string. str=”I am a string”; //Works fine and compiles
Errors are caught at compile time. Errors are caught at runtime
Since the compiler knows about the type and the methods and properties of the type at the compile time itself Since the compiler comes to about the type and the methods and properties of the type at the run time.
Intellisense help is available for the var type of variables. This is because, its type is inferred by the compiler from the type of value it is assigned and as a result, the compiler has all the information related to the type Intellisense help is not available for dynamic type of variables since their type is unknown until run time. So intellisense help is not available. Even if you are informed by the compiler as “This operation will be resolved at run-time”.
will  throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value. Will compile

© 2015, www.techkatak.com. All rights reserved.