What is the difference between var and dynamic in C#?

Many people have expressed confusion around the difference between var and dynamic in C#.  For both of them, the type is inferred rather than explicitly declared. 
dynamic test = 1;
var test2 = 2;
If I hover my mouse over the “var” in the code above, IntelliSense will show me that the compiler has correctly inferred that it is an Int32.  If I hover over “dynamic”, it will continue to be typed as “dynamic” since dynamic types aren’t resolved until runtime. 
However, var is statically typed, and dynamic is not. 
// Can a dynamic change type?  
dynamic test = 1;
test = "i'm a string now";  // compiles and runs just fine
var test2 = 2;
test2 = "i'm a string now"; // will give compile error
This is one of the key differences between dynamic and var.  A var is an implicitly typed variable that is inferred by the compiler, but it is just as strongly typed as if you had explicitly typed it yourself using “int test2 = 2;”.  A dynamic variable bypasses all compile-time type checking and resolves everything at runtime.  
I’ll comment out the last line in the code above to get the code to compile, and add some code to verify the types of the variables. 
// Can a dynamic change type?  
dynamic test = 1;
Console.WriteLine("Dynamic as " + test.GetType() + ": " + test);
test = "i'm a string now";  // compiles and run just fine
Console.WriteLine("Dynamic as " + test.GetType() + ": " + test);
var test2 = 2;
//test2 = "i'm a string now"; // will give compile error
Console.WriteLine("Var as " + test2.GetType() + ": " + test2);
This produces the following output:
Dynamic as System.Int32: 1
Dynamic as System.String: i'm a string now
Var as System.Int32: 2

0 comments:

Post a Comment