Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Difference between Object, Dynamic and Var

0.00/5 (No votes)
31 Jul 2011 1  
A list of differences between the three types of the variables Object, Var and Dynamic.

In this post, I am going to write the points about the three types of the variable, Object, Var and Dynamic. Most developers are not able to get what is the difference between these three kinds of variables.

ObjectDynamicVar
Able to store any kind of value, because object is the base class of all types in .NET Framework.Able to store any type of the variable, similar to old VB language variable.Able to store any type of value but it is required to initialize at the time of declaration.

Compiler has little information about the type.

Compiler doesn't have any information about this type of variable.

It's compiler safe, i.e., compiler has all information about the stored value, so that it doesn't cause any issue at run-time.

Object type can be passed as function argument and function also can return object type.Dynamic type can be passed as function argument and function also can return object type.Var type cannot be passed as function argument and function cannot return object type. This type of variable can work in the scope where it is defined.

Require to cast object variable to original type before using it. So this assigning to object type and converting to original type called as Boxing and Un-Boxing for value type and for the reference type its casting of types. It's actually increasing the overhead when we do this both operation.

Allows to perform operation of given type once it gets cast any user defined or primitive data type.

Casting is not required but you need to know the property and methods related to stored type.No need to cast because compiler has all information to perform operation.
Cause the problem at run time if the stored value is not get converted to underlying data type.

Cause problem if the wrong method or property accessed because all the information about stored value gets resolved only at run time.

Doesn't cause problem because compiler has all information about stored value.
Useful when it doesn't have more information about the data type.Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code.Useful when getting result out of the linq queries. In 3.5 framework, it was introduced to support linq feature.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here