C# - Difference Between Var and Dynamic


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).

Let us see the difference between Var, and Dynamic.

1. 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.

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

2. 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.

Example

dynamic myobject = 10; 
myobject = test + 10; // No error
myobject = "hello"; // No error, neither compile time nor run time

Difference between Var and Dynamic type

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.
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;
var can not be parameter type. Dynamic can be parameter type.

Prev Next

Top Articles

  1. Why use C#
  2. How to use comment in C#
  3. How to use variables in C#
  4. How to use keywords in C#