Click here to Skip to main content
15,888,055 members
Articles / All Topics

Difference between Object, Dynamic and Var

Rate me:
Please Sign up or sign in to vote.
4.52/5 (19 votes)
30 Jul 2011CPOL2 min read 86.1K   21   17
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
GeneralMy vote of 3 Pin
khurram ali lashari3-Mar-14 15:21
professionalkhurram ali lashari3-Mar-14 15:21 
GeneralRe: My vote of 3 Pin
Pranay Rana6-Mar-14 0:37
professionalPranay Rana6-Mar-14 0:37 
GeneralRe: My vote of 3 Pin
khurram ali lashari6-Mar-14 6:09
professionalkhurram ali lashari6-Mar-14 6:09 
GeneralMy vote of 5 Pin
Pratik Bhuva31-Dec-13 3:17
professionalPratik Bhuva31-Dec-13 3:17 
QuestionNice one! check this blog also for more info about Var and Dynamic senthilvijayalakshmi.blogspot.in/2013/03/difference-between-var-and-dynamic.html Pin
senthilstayss7-Mar-13 17:55
senthilstayss7-Mar-13 17:55 
QuestionNot an article Pin
bbirajdar16-Sep-12 23:20
bbirajdar16-Sep-12 23:20 
GeneralMy vote of 3 Pin
GATzilla3-Aug-11 1:13
GATzilla3-Aug-11 1:13 
GeneralRe: My vote of 3 Pin
Pranay Rana3-Aug-11 18:40
professionalPranay Rana3-Aug-11 18:40 
GeneralRe: My vote of 3 Pin
GATzilla21-Nov-11 16:25
GATzilla21-Nov-11 16:25 
GeneralMy vote of 4 Pin
sachin10d1-Aug-11 19:36
sachin10d1-Aug-11 19:36 
GeneralRe: My vote of 4 Pin
Pranay Rana3-Aug-11 18:40
professionalPranay Rana3-Aug-11 18:40 
QuestionAbout var Pin
Jaime Olivares31-Jul-11 5:19
Jaime Olivares31-Jul-11 5:19 
Bug[My vote of 1] Too many technical errors Pin
GATzilla29-Jul-11 23:35
GATzilla29-Jul-11 23:35 
The article is poor. I won't touch the language quality of the article, although it's rather poor English. I will cover technical errors. In my comment, quotations will start with [x.n] tags which mean 'column x (Object|Dynamic|Var), row n'.

[Object.2] Compiler has little information about the type
That's not absolutely true. The compiler has all information about the variable type - it knows that it's System.Object. It might not know the type of the instance the variable holds reference to, but the same is true for a variable of any type referencing an instance of a child type. In any case, compiler knows the type and verifies our code according to that information - it will only allow us use the System.Object members safely.

[Dynamic.2] It's compiler safe i.e compiler has all information about the stored value
Totally wrong. Compiler has no information on the referenced instance. It compiles dynamic variables into local variables of type System.Object in Common Intermediate Language (CIL). The reason why the compiler will never issue an error when calling methods of a dynamic variable is that it doesn't care. When I define a dynamic variable, I tell the compiler 'Hey, I don't want you to resolve the call target at compile-time, I want you to generate code which will do that at run-time.' dynamic keyword shifts usually statically typed c# towards dynamically typed languages like JavaScript, Python, Ruby, etc.

[Dynamic.2] so that it doesn't cause any issue at run-time.
Again totally wrong. A call on a dynamic variable will generate run-time target resolution code which will throw an exception if the call target cannot be resolved. That's a huge caveat of dynamically typed languages - you won't know if your code is wrong until you test all code paths.

[Var.2] Compiler doesn't have any information about the this type of variable.
Wrong. var is not even a variable type. It's a keyword that makes the compiler define the type of a variable implicitly based on the knowledge of the type of the initial value of the variable. Writing
C#
var i = 1;

instead of
C#
int i = 1;

just means 'Hey, compiler, I want you to analyze the initial value of the i and determine its type'. In CIL, however, both cases will compile into a variable of type System.Int32. Moreover, the following will compile:
C#
dynamic x = 0;
var y = x; // y now is a dynamic typed variable
y.CallMethodThatDoesntExist(); // so this will compile, but may fail at run-time.


[Dynamic.3] Dynamic type can be passed as function argument and function also can return object type
Supposedly, the sentence should read as 'Dynamic type can be passed as function argument and function also can return dynamic type'.
Well, technically it's true, but developer must realize that dynamic cannot be passed as function argument, because CIL doesn't know such a type. It's object that is passed to a function, since a dynamic variable is an object variable with static code verification turned off. The only difference is that there will be DynamicAttributes attached to parameters and return value to indicate their dynamic nature. But still, another .NET language that doesn't know about dynamic typing might see that a method
C#
dynamic M(dynamic x){...}

is actually a
C#
object M(object x){...}


[Var.3] 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.
Again, this should read as 'Var type can not be passed as function argument and function can not return var type. This type of variable can work in the scope where it defined.'
I would rephrase this. A var variable can be passed into a method, because the compiler will infer the actual variable type, but you cannot define a method that takes a var parameter or returns a var.

[Object.4] Require to cast object variable to original type before using it
Well, I can cast it to any type. The only thing is that if the instance type doesn't inherit from or imlements the cast target, I will get an InvalidCastException.

[Object.4] So this assigning to object type and converting to original type called as Boxing and Un-Boxing.
Wrong. It's called 'Type Casting' and can be applied from any type and to any type. Boxing/unboxing relates only to value types. The difference is that when casting types, we just get a new reference to the same object, without affecting the object. But when boxing/unboxing, we move a value type instance from stack to heap or vice-versa, which means physical copying of the instance data between 2 memory regions.

[Object.4] It's actually increasing the overhead when we do this both operation.
Yes, it includes a couple of additional CPU instructions, but I wouldn't pay attention to this fact. Far worse problem is that when you use object variables and type casting, you cannot rely on the compiler to check your code. You won't know if your code is correct until you test all code paths. (From this point of view, using too many object variables is similar to using too many dynamic variables)

[Var.6] Useful when getting result out of the linq queries.
Well, not only. It's most useful when we work with anonymous types anywhere, because we cannot declare a variable of an anonymous type, so we have to declare it as var. And anonymous types are now used increasingly wide: RX library (IObservables and IQbservables), various DAL frameworks (LINQ to SQL, Entity Framework (well, this is LINQ), NHibernate), etc.
GeneralRe: [My vote of 1] Too many technical errors [modified] Pin
Pranay Rana30-Jul-11 3:20
professionalPranay Rana30-Jul-11 3:20 
BugRe: [My vote of 1] Too many technical errors Pin
GATzilla30-Jul-11 8:48
GATzilla30-Jul-11 8:48 
QuestionGood one!!!! Pin
Anil_Saran29-Jul-11 20:24
Anil_Saran29-Jul-11 20:24 
AnswerRe: Good one!!!! Pin
Pranay Rana29-Jul-11 23:11
professionalPranay Rana29-Jul-11 23:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.