C# 4.0 dynamic Keyword


Introduction

Generally, C# is statically typed languages and checked type at the compile time. Languages like Ruby, Python are dynamic and determined the objects at the run time. Visual C# 2010 introduces a new keyword, dynamic which is a static type, but an object of type dynamic bypasses static type checking. So C# can use the features of dynamic language. It was introduced for C# 4.0 only and not for .net 4.0.

Whenever you use the dynamic keyword you tell the compiler to turn off the compile time checking. For example

intellisense

You can notice intellisense is saying it is dynamic expression and operation will be resolved at runtime.  Consider above example:

dynamic dynamicString = "Test";
Console.WriteLine(dynamicString.GetType());
dynamic dynamicInteger = 9;
Console.WriteLine(dynamicInteger.GetType());

Above line of code will give an output. System.String and System.Int32.

Another thing is you can call any function and any property. If it is not declared yet, your code will still compile but you will get runtime exception.

dynamic dynamicString = "Test";
dynamicString.Display();
dynamicString.Name = "Pradip";

Note in above code actually dynamicString is String type but you can call method like Display() and property like Name which are not in String. Your code compile well but you will get run time exception.

var Vs dynamic?

You might be familier with the powerful var keyword from .net which is used for implicitly typed variables and for anonymous types. It is static and occurs at compile time. You can’t change the type of the variable at run time.

var varString = "Test";
varString.Display();

In above code, second line will result the compile time error.

Now lets look this piece of code.

dynamic dynamicString = "Test";
var varString = dynamicString;
varString.Display();

Now, varString is dynamic type and above code will compile. var is not a type, var keyword just instruct the compiler to infer the type from the variable’s initialization expression. So, we can use dynamic and var keyword together and they are mutually exclusive in nature.

Reflection and dynamic

Reflection is one way from which you can call invoke method (property and other also) dynamically. Compiler won’t throw any exception about even if there is no exception. But there will be complex long code in your program. For example to use String.Substring you need to write following code.

String str = "Pradip";
Type type = str.GetType();
 String subStr = (String)type.InvokeMember("Substring", System.Reflection.BindingFlags.InvokeMethod, null, str, new Object[] { 3 });

Now, using dynamic you can get same result with clean and neat code.

dynamic dynamicString = "Pradip";
String subString = dynamicString.Substring(3);

Of course, above example is not good enough to give explanation of using dynamic over reflection but you will find it better to use dynamic keyword in you application which uses reflection very much.

Adding/Removing method and property at runtime

Using dynamic keyword you can add/remove method or property from the object at the runtime. For this .net 4.0 provides ExpandoObject and DynamicObject classes defined in System.Dynamic namespace. Here is an example of adding property and method.

dynamic myObject = new ExpandoObject();
myObject.Name = "Pradip";
myObject.Display = new Action<String>(o => Console.WriteLine(myObject.Name));
myObject.Display(null);

COM Interop and dynamic

Many COM interop allow the variation in arguments type and has the return type as Object. So, there needs the casting to appropriate one to use it as the strongly typed variable. The magical dynamic keyword allows us to treat the object in COM signature as dynamic and hence prevents casting. As a result, our code will become more readable and clean.

Without dynamic we would write like this.

((Excel.Range)excelApp.Cells[1, 2]).Value2 = "Pradip";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 2];

And using dynamic we can write.

excelApp.Cells[1, 2].Value = "Pradip";
Excel.Range range2010 = excelApp.Cells[1, 2];

Finally

I hope, you got some knowledge about the NEW dynamic keyword in C# 4.0. The more you use it, the more you will be familier. For now we can say that dyanamic keyword has added the dynamic programming feature in statically typed language C#.

 

Advertisements