Differences between Object, Var and Dynamic type
Here I will explain the difference between Object, Var and Dynamic type with example or how to initialize it with example or which one is good to use.
Object | Var | Dynamic |
Introduce in c# 1.0 | Introduce in c# 3.0 | Introduce in c# 4.0 |
It can store any type of value because It is base class of type | ||
Initialization is not mandatory.
For ex.
Object x; //optional
| Initialization is mandatory.
For ex.
var x=5; // mandatory
| Initialization is not mandatory.
For ex.
dynamic x; //optional
|
We can modify the type after initialization.
For Example:
object x=5; //x is integer
x = “akhil”;//x is string Console.WriteLine(x);
Output: akhil
| We cannot modify the type after initialization. Otherwise it give compilation error.
For Example:
var x=5; //x is integer
x = “akhil”;//x is string Console.WriteLine(x);
Output: error at compile time
| We can modify the type after initialization.
For Example:
dynamic x=5; //x is integer
x = “akhil”;//x is string Console.WriteLine(x);
Output: akhil
|
Object type can be passed as method argument and method also can return object type.
For ex:
Add(object x) //can
{
}
| Var type cannot be passed as method argument and method also can return object type.
For ex:
Add(var x) //can not
{
}
| dynamic type can be passed as method argument and method also can return object type.
For ex:
Add(dynamic x) //can
{
}
|
Compiler has little information about the type at compile time so it can be caused the problem at run time. | Compiler has all information about the type at compile time so it can be caused the problem at run time. | Compiler has not any information about the type at compile time so it can be caused the problem at run time when wrong properties or method access. |
Useful when we don’t have more information about the data type. | Useful when we don’t know actual type i.e. type is anonymous. | Useful when we need to code using reflection or dynamic languages or with the COM objects, because you need to write less code. |