.NET life

HUGON Jérôme
Microsoft Certified Technology Specialist Microsoft Certified Application Developer Microsoft Certified Professional

Difference between var and dynamic

.NET

Category .NET  | Publication Date : 10/24/2010

var and dynamic types may create confusion. For both, the type is taking from the context rather than explicitly declared. But the differences are present on how to use them.

Consider the following example:

dynamic testDyn = 1;
var testVar = 2;

If I pass my mouse over the keyword var in the above code, the IntelliSense will show me that the compiler correctly inferred that this is an Int32. If I go over the keyword dynamic, it will continue to be a dynamic type. dynamic types are not resolved before running contrary to the var types.

Difference between var and dynamic - .NET

Difference between var and dynamic - .NET

What's going to happen when the type is changed? Consider the following example:

testDyn = "I change to a string";
testVar = "I change to a string";

Here's one key difference between dynamic and var. A var is a variable that is typed implicitly inferred by the compiler, but it is just as strongly typed if you had declared yourself. A dynamic variable bypasses all type checks at compile time and decide everything at runtime. Thus the above example throws an error when compiling:

Difference between var and dynamic - .NET

To illustrate the change of type at runtime, consider the following example:

dynamic testDyn = 1;
Console.WriteLine("Dynamic is a {0}: {1}", testDyn.GetType(), testDyn);
testDyn = "I change to a string";
Console.WriteLine("Dynamic is a {0}: {1}", testDyn.GetType(), testDyn);

The preceding code produces the following output when running:

Dynamic is a System.Int32: 1
Dynamic is a System.String: I change to a string


Related articles

Book: C# 4 Develop Windows applications with Visual Studio 2010

Visual Studio

Category Visual Studio  | Publication Date : 12/6/2010