.NET 4.0 dynamic Data Type

By | May 10, 2010

Microsoft implemented some nice dynamic features in .NET 4.0.
For instance the new data type “dynamic”.

Loading dynamically Libraries with .NET < 4.0 reflection can be tricky. In the following example you see how it works. (Well, there are multiple possibilities for this..)

Assembly asbMath = Assembly.LoadFrom(“Lib.dll”);
object objMath = asbMath.CreateInstance(“Lib.Math”);
Type tMath = asbMath.GetType(“Lib.Math”);
object objResult = tMath.InvokeMember(“Plus”, BindingFlags.Default | BindingFlags.InvokeMethod, null, objMath, new object[] { 20, 30 });
int nResult = (int) objResult;

First you load the DLL. Afterwards you create an object of the class and the type. With the type object you call the InvokeMember and set some strange parameters. 🙂
The result must be casted in the correct type. (In this example –> int)

In .NET 4.0 it’s much easier. Like in the example above you create an instance of the Math class.
Instead of loading the instance into a “object” you use the dynamic data type. (Line 2)
Then you only need to call your method. Here I call the method “Plus”. The result will be automatically casted into an integer.

Assembly asbMath = Assembly.LoadFrom("Lib.dll");
dynamic dynMath = asbMath.CreateInstance("Lib.Math");
int nResult = dynMath.Plus(20, 30);

But why does the compiler build without errors? This is because of the new data type. The type of the object will be determined during the runtime. So that means, the compiler can’t check if the method “Plus” really exists. If you change the method in the “Lib.dll” your project will still compile correct but you will get an runtime exception.

How about the performance? I ran the examples above and came to this result:
.NET < 4.0: 11ms .NET 4.0: 48ms You see, the new data type is easier to use but has some performance penalty.