Hello Friends, In this tutorial, we are going to learn Object vs Var vs Dynamic. This is also a very hot topic for interviewer nowadays.
Object vs Var vs Dynamic
- An object is the root class in the class hierarchy that represents the System.object type. An object was introduced with .NET 1.0. Since Object is the Base class in the Class hierarchy so it can store any kind of values.An object has following characteristics:
- Object type was introduced with C# 1.0.
- Object Type can be able to store any type of value.
- The compiler has little information about the object.
- Since Compiler does not have enough information about Object type so we need to cast it to actual type before using
- While casting to its original type object can cause a problem if the stored value is not getting converted to original type.
- Object Type can be used as a function argument or can be used as return type.
- Var type was introduced with C# 3.0.
- Similar to object type it can also store any type of value with the difference that we need to initialize var type at the time of declaration.
- The compiler has the complete information about the value stored in the var type. As compiler has the full information about the var type so it does not cause any error at run time. Var is type safe.
- Var type does not require any type conversion since the compiler has the complete information about the value of the var type.
- Since Compiler has complete information about the Var type and it does not require any type casting so it does not cause any problem at run time.
- We cannot use var type as a function argument and return type.
- The dynamic type was introduced with the release of C# 4.0.
- Similar to object type and var type dynamic type can also store any type of value.
- The compiler does not have the complete information about the value stored in the dynamic type. So it can cause an error at run time.
- Dynamic type does not require any casting but we need to know about the properties and methods related to stored type.
- It can cause a problem at run time if matching property will not find.
- We can use dynamic as a function argument and return type.
Hope you understand the difference between Object, Var and Dynamic. I will appreciate your feedback, comments and Suggestions.