C# - Object Versus Var Versus Dynamic

So right now in C# we have the Object class, and the var and dynamic types. At first look, they all seem to do the same job, but not really.

Then the question is, what is the difference between Object, var and dynamic? And when should we use them?

So here is the answer.


The object class in C# represents the System.Object type, which is the root type in the C# class hierarchy. Generally we use this class when we cannot specify the object type at compile time, which generally happens, when we deal with interoperability.

Let's have an example. The following example explains that the variable amount, of which the type is object, but at run time we can get the actual type of that variable that is stored in the variable.


Let's perform a mathematical operation on it.


Why are we unable to perform a mathematical operation on it and instead get an error message but in the previous example we get the type of Amount as System.Int32. If the amount is a Systme.Int32 type and we can store an integer value in it then why are we unable to apply a simple mathematical operation?

Here is the reason. Actually, an object requires explicit type conversion before it can be used. We can store anything in the object type variable but for performing an operation we must type cast it. Because C# is a statically typed language so it will throw an exception when we start performing any operation on it without proper type casting.



The var type was introduced in C# 3.0. It is used for implicitly typed local variables and for anonymous types. The var keyword is generally used with LINQ.

When we declare a variable as a var type, the variable's type is inferred from the initialization string at compile time.


We cannot change the type of these variables at runtime. If the compiler can't infer the type, it produces a compilation error.



The dynamic type was introduced in C# 4.0. The dynamic type uses System.Object indirectly but it does not require explicit type casting for any operation at runtime, because it identifies the types at runtime only.


In the code above we are assigning various types of values in the variable amount because its type is dynamic and dynamic delays determination of the type until execution. All dynamic types variables enjoy the party at runtime.


Up Next
    Ebook Download
    View all
    View all
    Founded in 2012 by Red Ant Corp, Red Ant Corp & Associates Consulting (Red Ant Corp).