Wednesday, November 26, 2008

C# 4.0 “dynamic” versus “var”

The C# language is evolving so fast that it does take effort to keep up with Anders Hejlsberg, C#’s designer at Microsoft :)

Talking about the next version of C# in this video, Anders describes implementing a runtime operation called “dynamic” that eliminates all type safety for a variable. This essentially means that until the code is run, there is no way to determine if operations on the variable will fail.

There seems to be confusion about dynamic and var, so here is my 2 cents worth:

An example of using "var":


//While using “var”, the compiler essentially figures out the
//type of the variable using type inferencing
var a = “G’Day Mate!!!”;

//The below operation can be validated for errors at compile time (as opposed
//to runtime in the case of using “dynamic”)
a = a.ToUpper();



An example of using "dynamic":

//Sample dynamic instantiation
dynamic dyn = GetObject();

//An attempt to run dynamic code
//Only after we run this code, we will know whether we have errors
dyn.Walk();

0 comments:

  Personal Web Log of Simeon Lobo, 2001 - 2009

Back to TOP