Monday 11 August 2014

Difference between Object and Var and Dynamic type in C#

C# is rich in data type. It provides three types Object, Var and Dynamic to store data of any type. In this article, I am trying to explore the differences among these three.

Difference between Object, Var and Dynamic type

Object
1.       Object was introduced with C# 1.0
2.       It can store any kind of value, because object is the base class of all type in .NET framework.
3.       Compiler has little information about the type.
4.       Object type can be passed as method argument and method also can return object type.
5.       Need to cast object variable to original type to use it and performing desired operations.
6.       Cause the problem at run time if the stored value is not getting converted to underlying data type.
7.       Useful when we don’t have more information about the data type.

Var
1.       Var was introduced with C# 3.0
2.       It can store any type of value but It is mandatory to initialize var types at the time of declaration.
3.       It is type safe i.e. Compiler has all information about the stored value, so that it doesn't cause any issue at run-time.
4.       Var type cannot be passed as method argument and method cannot return object type. Var type work in the scope where it defined.
5.       No need to cast because compiler has all information to perform operations.
6.       Doesn't cause problem because compiler has all information about stored value.
7.       Useful when we don’t know actual type i.e. type is anonymous.

Dynamic
1.       Dynamic was introduced with C# 4.0
2.       It can store any type of the variable, similar to old VB language variable.
3.       It is not type safe i.e. Compiler doesn't have any information about the type of variable.
4.       Dynamic type can be passed as method argument and method also can return dynamic type.
5.       Casting is not required but you need to know the properties and methods related to stored type.
6.       Cause problem if the wrong properties or methods are accessed because all the information about stored value is get resolve only at run time.
7.                  7           Useful when we need to code using reflection or dynamic languages or with the COM objects, because             you need to write less code.

No comments :