.NET Articles

Difference between Object, Dynamic and Var in C#


Object

Object variable can store any type of value. Casting is required to access object value. See the below example.

        public class Emp
        {
            public string Name { get; set; }
            public string Role { get; set; }
        }
        

        Emp _emp = new Emp{ Name = "Micheal", Role = "Lead" };
        
        Object _obj;
        //Assgin Emp class instance
        _obj = _emp;

        //Casting to access Emp class
        Emp _empObj = (Emp)_obj;
        Console.WriteLine(_empObj.Name);	//Output: Micheal
    

Var

Var variable can store any type of value. Type initialization is required at the time of declaration. It is not possible to reinitializing different type. See the below example.

        var _var = new Emp() { Name = "Micheal", Role = "Lead" };
       Console.WriteLine(_var.Name);	//Output: Micheal
       _var = "test"; // Throws error. Reassigning to different type (String) throws error.  

Anonymous type:

Using Var, you can create properties without creating the class. This is called as anonymous type.

     	var _varNoClass = new { Company = "XYZ",Country="US", Emp = _emp };         

_varNoClass shows three properties as shown in below screenshot.

Anonymous type

Dynamic

dynamic is .net 4.0 framework feature. It can store any type. You can reinitialize different types. It doesn’t show any compilation errors. It shows the error in run time only.

      	dynamic _dyn = new Emp() { Name = "Micheal", Role = "Lead" };
     	Console.WriteLine(_dyn.Name);	//Output: Micheal

If you hit “.”, intellisense doesn’t show properties of class Emp. See the below screenshot.

Dynamic example
   	Console.WriteLine(_dyn.NameASDF);    

NameASDF is invalid property of Emp class. This doesn’t give any compilation error but throws error” 'Emp' does not contain a definition for NameASDF” in runtime.

    	string name = "Alex";
   	_dyn = name;
   	Console.WriteLine(_dyn.Name);	//Output: Alex    

Now the type of dynamic variable _dyn is string(previously Emp type). dynamic variable can be reinitialize with different types which is not possible in Var type.