Sunday, May 24, 2009

C# 4.0's new Keyword 'dynamic'

CSharp 4.0 introduces a new keyword dynamic. This keyword is introduced in C# to make interaction of CSharp with Dynamic Languages, JavaScript, Python and Ruby etc, easier. About the dynamic keyword, Anders Hejlsberg says "The dynamic keyword says that the static type of this variable is 'dynamic'.". i.e. I don't know the type of this variable at compile time. So, leave it untill run time. But I can call any method defined on the type. These method calls would be made to the actual method defined. If that method is not defined, a run time exception would be thrown.

For example, we have a JavaScript calculator. We want to use that in C# 3.0 or below. We will have to go to the .NET Reflection. Reflection is very slow mechanism. But with C# 4.0, we will write:

GetJSCalculator() method will return the JavaScript calculator at run time. For more information visit these links:

No comments:

Post a Comment