[C #] object, var and dynamic what’s the difference?

  • var - Is a way of inferring a type and only variables can be declared.
  • object and var - All information of type / variable is known at compile time.
  • Dynamic - information is known only at runtime and can be applied to properties, methods return, parameters, objects etc.
  • Object and var: are reserved words whereas dynamic is not. That way if you define a variable called dynamic it will be compiled in C # 4.0.

Object

Refers to the type System.Object that is the basis for all other types, whether they are reference types or type-values.
A variable / parameter of this type allows any kind of data to be associated, and if it is a class, a simple assignment occurs, and if it is a value-type, first the boxing of that value occurs, and then an assignment.

Boxing

In the boxing process what happens is that a new object is allocated in memory and the value of the variable is copied to it. In practice, what happens is that we take the type by value and place it inside a new object. From that moment we can use our type by value as a type by reference.

Unboxing

The process of unboxing is exactly the opposite of boxing. To perform actions where you do not need the weight of a type by reference, unboxing brings back the type by value. It works as if we had removed the envelope from our variable and left it with only its value.


var

This is what is called syntactic sugar. It’s just a key word that is used for the compiler to guess the type at compile time. This is called type inference. I’ll be direct:


Dynamic

This is a key word that lets you call methods and properties of any object, without knowing its type. This is known as late-binding, that is, it is associating the call to the target method / property only at the time the call is made.
Note that when doing the dispatch, you will use a dispatcher that acts exactly like C # (or Visual Basic, if you are using dynamic in VB). This dispatcher tries to find the method / property / operation in the same way that C # would do … and if it fails an exception will be thrown indicating that the call can not be made.