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 Var, and Dynamic that allow you to store data of any type without regard to its exact data type. The type 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).
Var Keyword
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.
Dynamic keyword
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.
Difference
Let us see the difference between Var and Dynamic.
1. Type Inference
var number = 10; // Compiler infers type as int
dynamic number = 10; // Type determined at runtime
2. Type Checking
var number = 10;
number = "Hello"; // Compile-time error: cannot convert from 'string' to 'int'
dynamic number = 10;
number = "Hello"; // No compile-time error, but can cause runtime errors
3. Casting
var number = 10;
int doubled = number * 2; // No casting required
dynamic number = 10;
number = number * 2; // No casting required
number = "Now I'm a string"; // Still no casting required
4. IntelliSense
5. Errors
S.No. | Var | Dynamic |
---|---|---|
1 | The object was introduced with C# 3.0 | Dynamic was introduced with C# 4.0 |
2 | 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 | No need to cast because the compiler has all information to perform operations. | Casting is not required. |
4 | 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 | var can not be parameter type. | Dynamic can be parameter type. |