Breaking News

Thursday, April 22, 2010

C# 4.0: dynamic 'contextual keyword'

There is a new type, a contextual keyword, called dynamic in C# v4.0; getting to much of a popularity among advanced programming.It is used to call operations of dynamic languages (DLR).

To put it simply, binding is the association of a symbol within a program with an address in memory. The term “binding”, in this case refers to the process of resolving types, members, and operations.
  • Static binding happens at compile time, where a compiler identifies, resolves, and throws exception if necessary, at compile time.
  • Dynamic binding refers to identification, resolution, and throwing of exception if any, during runtime.
Dynamic binding in useful in cases where you know that a certain member, function, or operation would be available at run time. But compiler doesn’t know about that; the compiler would not throw any exceptions as well because it would just “trust you”, because you used dynamic keyword.
“A dynamic type tells the compiler to relax. We expect the runtime type of d to have
a Quack method. We just can’t prove it statically.” – (C# in a Nutshell Chap-4 Pg161)
dynamic dynTest = new Test();

dynamic means that all expressions using dynTest is bound at execution time, rather than at compile-time, and thus makes it behave dynamically.

dynamic versus var keyword

A lot of times dynamic is confused with the var keyword; and to prove that statement, following is such an example that creates quite a confusion.

//CODE 1
var varTest = new Test();

//CODE 2
dynamic dynTest = new Test();

Here, in CODE 1, var means the static type is inferred - in this case it's same as
Test varTest = new Test();

var is static typed - the compiler actually knows the type All the binding is still done entirely statically.

dynamic, in CODE 2, means that all expressions using dynTest is bound at execution time, rather than at compile-time, and thus makes it behave dynamically. Compiler won't check whether the AnotherTest() method exists - the behavior is determined at execution/run time.

Note that, somewhat on a tangent, if the object implements IDynamicMetaObjectProvider it could decide what to do with the call at execution time, responding to any method call - in other words, there doesn't have to be a "real" method called AnotherTest() at all.

This type of binding is also called “Custom Binding”; Custom binding occurs when a dynamic object implements IDynamicMetaObjectProvider (IDMOP). I’ll write more about custom binding sometime.

If you'd like to read more, here is a worth viewing, if you are short of reading time, article C# 4.0 – Dynamic Language Runtime by Microsoft's Bruno Terkaly with excellent visuals.

Happy dynamic’s! (0:

No comments:

Post a Comment

Designed By Published.. Blogger Templates