Monday, December 20, 2010

Implicitly Typed Local Variables Vs Dynamic Type


Implicitly Typed local variables are declared using “var” keyword. You must need to initialize value at the time of declaring variable. For an example
var counter = 5;
From the above example, Compiler will determine “counter” variable as an int type variable. If you forgot to initialize variable value then compiler will give error (“Implicitly-typed local variables must be initialized”).

Dynamic type is declared using “dynamic” keyword. You don’t require to assign value at the time of declaring variable. Like
dynamic counter;
Compiler doesn’t know about the value but when you set any value to the variable, the variable will hold that type and you can use it. It is similar to Object type. Like
dynamic counter;
counter = 5;
counter++;
counter = new Employee();
counter.Save();

Difference:
  • Developer will get intellisense support with “var” keyword. But you will not get intellisense support with “dynamic” keyword.
  • Implicit local variable give compile type error if any. Dynamic variable gives only runtime error if any.
  • Implicit local variable assign value at the time of declaration only. Developer can change the value but can’t change the type. Dynamic variable gives facility to assign any type of value at anytime. For example if you assign value 5 (numeric) to implicit typed variable then you can’t assign any other type (string, Boolean etc) to that variable. For dynamic type, you can assign any type of value anytime.

No comments:

Post a Comment

DotNet Code Guru