Difference between var and dynamic keywords in C#

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
name = "Seek your career.in"; // initialization
Above 2 lines code gives compile time error. Below line will work perfectly.
var name = "Seek your career.in";
Initialization can be done later after declaration.
eg. dynamic name; //declaration
name = "Seek your career.in"; // initialization
Above code will work perfectly.
name = 100; // it will also work fine.
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.

Var Keyword

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’).

Dynamic Keyword

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.