Object vs Dynamic vs Var and ExpandoObject

The Object type has existed since the beginning of C#, in other words C# 1.0 and exists at System.Object. Var comes next in C# 3.0 followed by the dynamic keyword in C# 4.0.

Object

Now object comes from C# 1.0 and derives from System.Object and we can assign any value to this reference.

  1.     static void Main(string[] args)    
  2.     {    
  3.         object iobj = 10; //Perfectly Legal    
  4.         var ivar = 10;    
  5.         dynamic dvar = 10;    
  6.         Console.WriteLine(iobj.GetType());// gives System.int32.    
  7.         Console.WriteLine(ivar.GetType());// gives System.int32.    
  8.         Console.WriteLine(dvar.GetType());// gives System.int32.    
  9.         // Reason-This is  because int is the type  value stored IN ALL REFRENCE TYPE.    
  10.       1)    
  11.       iobj = iobj + 10; //Illegal and gives compile time error.    
  12.         //Reason- at compile time its is object type,so compiler doesnt have any idea how to add object              type,for this you need to cast in integer.    
  13.         //Looking at IL for this:    
  14.         // .locals init ([0] object iobj)                 
  15.         //In order to add ,you need explicit cast     
  16.         iobj = (int)iobj + 10;    
  17.         Console.WriteLine(iobj); //Perfectly legal    
  18.         2)                      
  19.         ivar = ivar + 10; //Perfectly legal     
  20.         //Reason-At compile time,it is not var type but int type,let us see IL    
  21.         //.locals init ([1] int32 ivar,     
  22.         Console.ReadLine();     
  23.   
  24.         3)                 
  25.         dvar = dvar + 10; //Perfectly legal     
  26.       //Reason-At compile time,it is not var type but int type,let us see IL    
  27.          Console.ReadLine();      
  28. }    
So what's the difference between var and dynamic?

 

  1. var was introduced in C# 3.0. Dynamic was introduced in C# 4.0.

  2. var is statically typed, in other words the data type of var is inferred at compile time. Dynamic is a dynamic type and the value type is inferred at runtime.

  3. Vars are initialized during declaration. A dynamic can be initialized at runtime.

  4. Var cannot be used to create a return type of a function or property. Dynamic can be used as the return type or properties.

  5. var cannot change the data type. A dynamic can change its data type later.
    1. //var val = 10;    
    2. //val = "string";//Illegal as now it need to cast in into string    
    3. dynamic dynam = 10;    
    4. dynam = "string1"//Perfectly Legal                
    5. Console.ReadLine();   

"As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time." -MSDN

The following are the usage of these two.

  • They are used to reduce the number of lines of code. We do not need to write the type name again and again.
    1. Dictionary<string, Control> d = new Dictionary<string, Control>();  
    That can now be written simply as:
    1. var d = new Dictionary<string, Control>();  
    2.   
    3. dynamic d = new Dictionary<string, Control>();   
  • They are used extensively in anonymous methods. You wouldn't be able to declare a variable of an anonymous type if you always need to include the type name as part of the variable declaration.
  • COM interop.
  • Reading XML, JSON without creating custom classes.

Difference between object and dynamic

Dynamic tells the compiler that the data type can be anything so the compiler doesn't interfere and hence dynamic gives no compile-time error but will definitely give a runtime error is all is not good (in other words runtime error).

The following code will work properly for dynamic but not if dynamic is replaced by object. (The reason is explained in the preceding in the object type discussion.)

  1. dyn = 10.0;    
  2. dyn = dyn + 10;    
  3.     
  4. dyn = "10";    
  5. dyn = dyn + 10;  
So if dynamic can take any data type, can we pass it to another function expecting something other data type and crash?

Assume we have a function:
  1. public static void display(string abc)    
  2. {    
  3.     Console.WriteLine(abc);    
  4. }   
Now we have:
  1. object iobj = 10;    
  2.       display(iobj);    
  3.   
  4.       dynamic dynam = 10;    
  5.       display(dynam);        
  6.       Console.ReadLine();  
Here, the first one will not compile and the second one will compile but give a runtime error.

Dynamic suppresses the compiler logic.

With the dynamic keyword, one interesting object comes out to be ExpandoObject.

In order to emulate the dynamic functionality of adding members to objects at runtime, .Net comes with the IDynamicMetaObjectProvider interface. Classes implementing it will have a full dynamic behavior.

A useful class in version 4 of the .NET Framework is ExpandoObject. It is a built-in implementation of the IDynamicMetaObjectProvider interface and it allows dynamically adding members at runtime, like in the following example:
  1. dynamic contact = new ExpandoObject();    
  2. contact.Name = "GOGO";    
  3. contact.Phone = "206-555-0144";    
  4. contact.Address = new ExpandoObject(); //Notice this line    
  5. contact.Address.Street = "Main St";    
The code is taken from MSDN. This has the following two interesting features.
  1. Here, we have not used ExpandoObject=new ExpandoObject () because doing so will make it a statically-typed object of the ExpandoObject type. And of course, statically-typed variables cannot add members at run time.

  2. To add another node to the contact node, simply add another ExpandoObject. (In other words contact.Address = newExpandoObject()).

Up Next
    Ebook Download
    View all
    Learn
    View all