Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Difference between Object, Dynamic and Var

DZone's Guide to

Difference between Object, Dynamic and Var

·
Free Resource
In this post I am going to write the points about the three type of the variable Object, Var and Dynamic. Most of the developer not able to get what is difference between this three kind of variable.
Object Dynamic Var
Can able to store any kind of value, because object is the base class of all type in .net framework. Can able to store any type of the variable, similar to old VB language variable. Can able to store any type of value but it require to initialize at the time of declaration.

Compiler has little information about the type

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.

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

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 can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it 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. It's actually increasing the overhead when we do this both operation.
Allows to perform operation of given type once it get cast any user defined or primitive data type.
Casting is not require 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 is get resolve only at run time

Doesn't cause problem because compiler has all info about stored value.
Useful when 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 introduce to support linq feature.

CodeProject
Topics:

Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}