There are many different datatypes available in C#, and you can declare a variable type for a particular datatype, such as int, string, or bool. C# is rich in data type. It includes several datatypes like Object, Var, and Dynamic that allow you to store data of any type without regard to its exact data type. The type keyword Object was introduced with C# 1.0, Var was introduced in C# 3.0 (.NET 3.5 with Visual Studio 2008) and the type Dynamic was introduced in C# 4.0 ( .NET 4.0 with Visual Studio 2010).
Let us see the difference between Object, Var, and Dynamic.
The object was introduced in C# 1.0. It can store any type of value because it is the base class for all types in .Net Framework. You need to cast the object variable to the original type to use it. You need to be very careful while using objects because it will create problems at runtime if it is not able to convert to a specific type while being typecast.
Example
object myobject = 10;
myobject = test + 10; // Compile time error
myobject = "hello"; // No error, Need Boxing here
Var keywords are introduced in C# 3.0. It is compile time variable and does not require boxing and unboxing. Since Var is a compile time feature, all type checking is done at compile time only. Once Var has been initialized, you can't change type stored in it.
Example
var myobject = 10; // after this line test has become of integer type
myobject = test + 10; // No error
myobject = "hello"; // Compile time error as test is an integer type
It was introduced in C# 4.0. It can store any type of value, and the type of the variable is unknown until runtime. so it will not support IntelliSense. It's not mandatory to initialise at declaration time. Dynamic types can be passed method parameters.
dynamic myobject = 10;
myobject = test + 10; // No error
myobject = "hello"; // No error, neither compile time nor run time
S.No. | Object | Var | Dynamic |
---|---|---|---|
1 | The object was introduced with C# 1.0 | The object was introduced with C# 3.0 | Dynamic was introduced with C# 4.0 |
2 | The Compiler has little information about the type. It's not compiler safe. | It is type-safe i.e. Compiler has all information about the stored value | The compiler doesn't have any information about the type of variable. |
3 | Need to cast the object variable to the original type to use it. | No need to cast because the compiler has all information to perform operations. | Casting is not required. |
4 | No need to initialize at the time of declaration. e.g - object str; |
Need to initialize at the time of declaration. e.g - var str="tutorialstrend"; |
No need to initialize at the time of declaration. e.g - dynamic str; |
5 | Object can be parameter type. | var can not be parameter type. | Dynamic can be parameter type. |
6 | Intelligence available | Intelligence available | Intelligence not available |