Concept of Dynamic, Var and Object Type in C#

Object

C#, being object oriented, has everything derived from object type, be it directly or indirectly.

Some important points about "object" type:

  1. It is a compile time variable type
  2. It requires unboxing when you want get the actual type of the value assigned t it.
  3. The operation of unboxing makes it slow.
  4. It supports both  boxing and unboxing.
  5. Run time exceptions may occur during unboxing.

Sample code for the same,

  1. objectobj = 1;  
  2. obj = obj + 1; // Compile time error because implicit conversion is not possible  
  3. obj = (int)(obj) + 1; //no error as we did the conversion.  
  4. obj = "hello"// No error as boxing happens here  
  5. obj = (int)(obj); //no type checking is performed hence run time exception  
Var

Var is also a compile time variable type but the way in which it differs from object type is that it does not require boxing and unboxing.

Some important points about "var" type:

 

  1. All type checking is done at compile time only.
  2. Once Var has been initialized, you can't change type stored in it.
  3. No boxing/unboxing, hence it is memory efficient.

Sample code,

  1. vartypevar = 1; // this assignment decides the type of variable "typevar" as integer type  
  2. typevar = typevar+ 10; // No error  
  3. typevar= "hello"// Since, var does compile time type check and hence assigning a string value will result in error.  
Dynamic

Dynamic is a run time variable type.

Some important points about dynamic variable types:

 

  • A value can be assigned to a dynamic type variable either at run time or compile time.
  • The value assigned to a dynamic type can be changed at any time - run time or compile time.
  • Only run time exceptions occur when we use dynamic type variable.
  • "RuntimeBinderException" exception occurs when you try access a method that does not exist in dynamic type.

Sample code,

  1. dynamictestdynamic = 10;  
  2. testdynamic = testdynamic + 10; // No error  
  3. testdynamic = "hello"// No error, neither compile time nor run time  
Other points

 

  1. Dynamic type and object type variables can be passed as arguments to methods.

  2. Dynamic type need not to be initialized during declaration while var type needs to be initialized.

  3. Since dynamic type and object type are more or less the same, we cannot write overloaded methods. An example of this is explained below,
    1. public void calculate(dynamic check) { }   
    2. public void calculate(object check) { }  
    This code results in a compile time error.