Difference between Var and Dynamic

Var Keyword: All the methods, property or any other information are available at compile time.

Dynamic Keyword: As the name suggest all the method, property and other information is available at run time.

Let's understand it with a example.

  1. class Employee  
  2. {  
  3. public int Id { getset; }  
  4. public string Name { getset; }  
  5. public int Salary { getset; }  
  6. }  
  7. var employee=new Employee(){ Id=1, Name="Diwakar", Salary=6000 } ;  
  8. Console.WriteLine("Employee First Name:"+employee.Name);  
  9. Console.WriteLine("Employee Last Name:"+employee.Last); // This line will give compile time error, As Employee class does not have Last Property.  
  10. dynamic employee = new Employee() { Id = 1, Name = "Diwakar", Salary = 6000 };  
  11. Console.WriteLine("Employee Name:"+employee.Name);  
  12. Console.WriteLine("Employee Last Name:"+employee.Last);//This line will compile successfully but it will throw exception at runtime.