Difference Between Var and Dynamic in C#

The var keyword

The var keyword was introduced in C# 3.0 and variables declared with var are statically typed. Here, the type of variable declared is decided at the compile time. Variables which are declared as var should be initialized at the time of declaration. By looking at the assigned value, the compiler will decide the variable type. As compiler knows the data type of the variable at compile time, errors will be caught at that time only. And Visual Studio 2008 and later versions will show the IntelliSense for var type.

Example
  1. var obj "c-sharp corner";  
 In the above sentence, obj will be treated as a string 
  1. obj = 10;  
In the above line, the compiler will throw an error, as compiler already decided the type of obj as String and assigned an integer value to string variable violating safety rule type.
 
The dynamic keyword

The dynamic keyword was introduced in C# 4.0 and variables declared with dynamic were dynamically typed. Here, the type of variable declared is decided at runtime. Variables which are declared as dynamic don't need to initialize the time of declaration. The compiler won't know the variable time at the time of compiling, hence errors can't be caught by the compiler while compiling. IntelliSense is not available since the type of variable will be decided at runtime.
 
 Example
  1. dynamic obj = "c-sharp corner";  
 In the above code, obj will be treated as a string.
  1. obj = 10;  
The comipler will not throw any error, though obj is assigned to the integer value. The compiler will create the type of obj as String and then it recreates the type of obj as an integer when we assign an integer value to obj.
 
I hope you have understood the difference between var and dynamic.
 
Happy learning.