These are major differences between Var and Dynamic Keywords are below :
Var | Dynamic |
---|---|
Var is introduced in C# 3.0 | Dynamic is introduced in C# 4.0 |
Datatype of variable is decided at compile time. | Datatype of variable is decided at runtime. |
Initialization in needed at the time of declaration. eg. var name; //declaration |
Initialization can be done later after declaration. eg. dynamic name; //declaration |
Intellisense works here as the compiler know the type of data stored in the variable. | Intellisense is not available because the data type is decided at runtime. |
Example: var code = “ABC”; //when compiler compile this line it decides that variable “code” is of string type. code = 1; //error – now cannot store other type of value. |
Example: dynamic code = “ABC”; //when compiler compile this line it creates variable “code” of string type. code = 1; //here compiler recreates the variable “code” of type Integer and works fine. |
Note :
From the above table of differences we can conclude that CLR define the type of var keyword at compile time. So all the error checking is done at compile time only because here in this case compiler know the type of variable.
In the above image, a variable “myString” is declared. When we type letter ‘L’ with the dot operator to access the properties of the mentioned variable, we will get intellisense. Here as the compiler know the type of variable thereby giving us all the methods and properties of string type.
Moreover, if you write : myString.length in the above example. Then the compiler will give compile time error. (The property Length has capital ‘L’).
In the above image you can see that here we are not getting any intellisense. Because compiler dont know the type of data stored in ‘myString’ variable. It will be resolved at runtime. No compile time error checking is done here.