What is different between this two variable definitions?
object oVar; dynamic dVar;
Performance? Memory allocation? Benefits?
Object is useful when we don't have more information about the data type. Dynamic is useful when we need to code using reflection or dynamic languages or with the COM objects and when getting result out of the LinQ queries.
Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime.
It is definitely a bad idea to use dynamic in all cases where it can be used. This is because your programs will lose the benefits of compile-time checking and they will also be much slower.
One variable is typed as object
by the compiler and all instance members will be verified as valid by the compiler. The other variable is typed as dynamic
and all instance members will be ignored by the compiler and called by the DLR at execution time.
It has nothing to do with either performance or memory allocation. The dynamic
type is a static type that the compiler somewhat ignores. It gives you the ability to use duck typing in a statically typed language which provides a lot of flexibility (especially when dealing with components written in languages that are more dynamic).
I would definitely recommend that you read up on the following topics:
object
is valid for all .NET versions.
It is the base type that all other types inherit from, so any type can be cast to object
.
You can't dynamically add and change anything on a variable declared as object
.
The declaration is a statically typed and checked by the compiler.
dynamic
is new for .NET 4.0.
It allows you do dynamically add and change properties and methods without the compiler checking them (so if what you wrote is wrong you will only find out at runtime).
In terms of memory allocation - not much of a difference. Both are reference types and whatever object assigned to either will already have memory allocated to storing it.
In regards to performance, since the DLR gets involved with dynamic
, there will be some overhead. You will need to test and see.
As for other benefits - dynamic
really helps with readability when dealing with dynamic objects/data, for example XML files. It also helps with reflection in a similar way.
Of course, if you want to have dynamic objects, you can't use object
and have to use dynamic
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With