vote buttons
2
1
beginner
0
intermediate
0
advanced
21-Jan-2015 01:12 UTC
K Bonneau
350

1 Answers

vote buttons
1

When you use the var keyword, you tell the compiler to automatically determine the type of the variable based on the value assigned.

When you use the dynamic keyword you tell the compiler to turn off compile-time checking. However the type checks still do happen during runtime, and instead of compile time errors, you get runtime errors.

The following code won't compile as the compiler has inferred the value of v to be string, and ++ is not defined for a string.

var v = "some string"; //compiler infers type of v is string
v++; // compiler error here. The code does not compile.

The below code compiles fine as the compiler checks are turned off for dynamic. However if we run it, we will get a Runtime exception when we attempt to increment a string.

dynamic d = "some string"
d++;

For var the type of the variable is determined at the time of declaration and the type does not change throughout the lifetime of the variable. However for a variable declared using the dynamic keyword, the variable can assume different underlying types.

dynamic d = "some string"; // d is string
d = 100; // d is now int

With dynamic we lose compile time checks, so it is generally advised to avoid using dynamics unless necessary. Following quote from MSDN nicely summarized when use of dynamics is justified:

As a developer, you use the dynamic keyword with variables expected to contain objects of uncertain type such as objects returned from a COM or DOM API; obtained from a dynamic language (IronRuby, for example); from reflection; from objects built dynamically in C# 4.0 using the new expand capabilities.

21-Jan-2015 01:15 UTC
K Bonneau
350