Pages

Wednesday, August 25, 2010

dynamic Versus var

At first glance, the difference between dynamic and var may not be entirely obvious.
With either, you do not have to tell the compiler explicitly what type of data you’re
working with—the compiler ultimately ensures that the right thing happens. For ex-
ample, whether using dynamic or var, the + operator has the same effect that it would
have if you had used it with explicitly typed variables. So why do we need both?
The difference is timing: var does things much earlier. The C# compiler insists on being
able to work out what type of data is in a var variable at compile time. But with
dynamic, it works it out at runtime. This means there are some things you can do with
dynamic that you cannot do with var. As Example 18-4 showed, you can use dynamic
for the arguments of a function declaration, and also for its return type. But this would
be illegal with var:
static var WillNotCompile(var a, var b) // Error
{
return a + b;
}

The compiler has insufficient information to work out at compile time what the argu-
ment and return types are here. But with dynamic, that doesn’t matter—the compiler
doesn’t need to know at compile type what type of data we’re using because it will
generate code that works out what to do at runtime.
Here’s another thing that dynamic can do that var cannot:
dynamic differentTypes = "Text";
differentTypes = 42;
differentTypes = new object();

The value in differentTypes changed from one line to the next. If we had used var, this
would have been illegal—a var variable’s type is determined by the expression used to
initialize it, so in this case, it would have been a string, meaning the second line would
have failed to compile.
So dynamic and var perfectly represent the distinction between dynamic and static: a
dynamic variable’s type (and consequently the behavior of any operations using that
variable) is determined at runtime; a var variable’s type is static—it is determined at
compile time and cannot change.

No comments:

Post a Comment