Pages

Monday, October 31, 2011

var vs dynamic keyword in C# 4.0

To put it as simple as possible, there is a simple difference between the C# ‘var’ and ‘dynamic’ keyword. When using the ‘var’ keyword, the type is decided by the compiler at compile time, whereas when using the ‘dynamic’ keyword, the type is decided by the runtime.

If you have been doing C# programming lately, you are already aware of the ‘var’ keyword, a strongly implicitly typed local variable for which the compiler is able to determine the type from the initialization expression - very useful when doing LINQ programming.

The ‘dynamic’ keyword was introduced in .NET 4.0 framework which also introduced the Dynamic Language Runtime (DLR) to accommodate dynamic languages like IronRuby and IronPython [are they dead?]. C# 4.0 provides access to this DLR using the new ‘dynamic’ keyword. C# is a statically typed language and the ‘dynamic' type automatically tells the compiler that it is a dynamic invocation, so ignore the compile time checking for this type. This also means that any invalid operations will only be detected at runtime.

Let’s see an example. Consider this piece of code:

var emp = new Employee();
emp.TakeBreak();


dynamic emp = new Employee();
emp.TakeBreak();

In the first case, i.e. when you are using the ‘var’ keyword, the type is statically inferred. So the line of code evaluates as

Employee emp = new Employee()


The compiler will check to see if a TakeBreak() method exists, if not, fail the compilation.

However that’s not the case when using the ‘dynamic’ type. Using the ‘dynamic’ type does not make it type-safe, hence the compiler is bypassed and the compiler does not check if the TakeBreak() method exists.

No type-safety? Why the hell do I need the ‘dynamic’ keyword for?

Well you need it because it is very useful in certain areas like interoperability. To start with an obvious one, it is very useful in dynamic languages that require runtime binding. Also, if you have an object declared as dynamic, then it’s no more your concern to handle how this object obtains it’s value. It’s value can be taken from a DOM object, or from a dynamic language like IronRuby, Reflection, Service or a COM API etc. The runtime takes care of the operations on this object.

The ‘dynamic’ type is also extremely useful when you are interoperating with Office Automation API’s. This saves you from casting everything from the object.

If you are interested, I will write a couple of more articles on the new ‘dynamic’ type and how you can use it to interoperate with the new Office Automation API’s. Let me know via the comments section if you care to see an example!

1 comment:

Unknown said...
This comment has been removed by the author.