Var was introduced in C# 3.0 and dynamic was introduced in C# 4.0. When we define a variable as var that means we cannot change its data type after first initialization and data type checking at compile time. When we define a variable as dynamic that means we can change its data type for any number of times during program execution and data type checking at run time.
- class vardynamic
- {
- public void show()
- {
- var a = "Hello var";
- dynamic b = “Hello dynamic”;
- Console.WriteLine("a: {0}", a);
- Console.WriteLine("b: {0}", b);
-
-
- b = 10;
- Console.WriteLine(b);
- }
- }
In above class, I have defined two variable a and b with var and dynamic respectively. Both the variables first initialized as string data type. If I uncomment two lines, program will give compile time error because variable a is first initialized as string that later changing to integer data type which is not possible. But b can be changed to string data type to integer data type because it is declared as dynamic.