What is difference between var and Dynamic ?

 Posted by Bhakti on 12/17/2009 | Category: C# Interview questions | Views: 8492

Var word was introduced with C#3.5(specifically for LINQ) while dynamic is introduced in C#4.0. variables declared with var keyword will get compiled and you can have all its related methods by intellisense while variables declared with dynamic keyword will never get compiled. All the exceptions related to dynamic type variables can only be caught at runtime.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: SheoNarayan on: 11/23/2011 | Points: 10
A very good description with example is also given in this post http://www.dotnetfunda.com/interview/exam4023-difference-between-var-and-dynamic.aspx.

Posted by: Senthilstayss on: 3/8/2013 | Points: 10
Nice one: -

1. The Var(Implicit typed local variable) keyword is used to define local variables.In case of Var , the underlying data type is determined at compile time itself based on the initial assignment.Once the initial assignment has been made with Var type , then it will become strongly typed.If you try to store any incompatible value with the Var type it will result in compile time error.


Var strNameList=new List<string>(); By using this statement we can store list of names in the string format.

strNameList.add(45); // This statement will cause the compile time error.

But in Dynamic type, the underlying type is determined only at run time.Dynamic data type is not checked at compile time and also it is not strongly typed.We can assign any initial value for dynamic type and then it can be reassigned to any new value during its life time.

dynamic test="Senthil";
Console.Writeline(test.GetType()) // System.String

Console.Writeline(test.GetType()) // System.Int32

test=new List<string>();
Console.Writeline(test.GetType()) //System.Collections.Generic.List'1[System.String]

It doesn't provide IntelliSense support also.It doesn't give better support when we give work with linq also.Because it doesn't support lambda expressions ,extension methods and anonymous methods.
Please check this one also for more info about Var and Dynamic:-


Login to post response