Dec 17, 2014

Difference between Object, Var and Dynamic type in C#

In interview I have faced a question many times like difference between Var, Object and Dynamic type. Below I am trying to explain please see.

Object can store any kind of value, because all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object. For performing desire operation its need to cast object variable to original type suppose you need to operation perform as int then need to type cost here like int a= (int)objValue, here objvalue is object type this is also called unboxing. Object is useful when we don’t have more information about the data type.
Note: Object introduced with C# 1.0
class MyClass
   static void Main()
      object a;
      a = 1;  

Var is strongly typed because var is implicitly typed local variable. Var can store any type of value but compulsory to initialize var types at the time of declaration. Var is type safe so no need to type cast at run time because compiler has all information about the stored value. Var type works in the scope where it is defined. Var is useful when type is optional means we don’t know actual type.
Note: Var introduced with C# 3.0
// Example #1: var is optional because 
// the select clause specifies a string 
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;
// Because each element in the sequence is a string,  
// not an anonymous type, var is optional here also. 
foreach (string s in wordQuery)

Dynamic typed declare variable is decided by the compiler at runtime time. Dynamic is not type safe means compiler doesn't have any information about the type of variable. It is not require casting but you need to know the properties and methods related to stored type. All the information about stored value is get resolve only at run time. Dynamic is useful when we need to code using reflection or dynamic languages or with the COM objects, because you need to write less code.
Note: Dynamic type introduced with C# 4.0
class Program
    static void Main(string[] args)
        dynamic dyn = 1;
        object obj = 1;
        // Rest the mouse pointer over dyn and obj to see their 
        // types at compile time.
        System.Console.WriteLine(obj.GetType()); // System.Int32
         // see below 
         dyn = dyn + 3; //success, no error
         obj = obj + 3; // get compile error here need to type casting