Home > .NET 4.0, C# > [EN] A little bit dynamic in C#

[EN] A little bit dynamic in C#

October 10, 2010 Leave a comment Go to comments

It’s a lot of time since .NET 4 came up (a lot in IT meaning). There are tons of new features that came with this release of .NET including Visual Studio. Some new features I described in a few posts earlier. This time I would like to tell something about the dynamic keyword in C# 4.0. There are thousands of explanations and examples that show the new feature (links at the end) – I show another view of this keyword – probably a drawback, that You should omit.

The power of the dynamic in C# 4.0 can be used with optional parameters in COM interoperation – like embedding PDF reader – before .NET 4.0 You should create a Type.Missing parameters in C# and place this object in each parameter of the COM procedure. When a COM procedure had 50 parameters, then You had to write each parameter, even if this parameter was not useful. With dynamic in C# You are able to do more, not only calls to COM are easier – thanks DLR [1] You are able to call procedures and functions (code) to Python, Ruby and other dynamic languages too. But don’t use dynamic everywhere and be careful – more features takes more time – the same is with dynamic. To visualize this I build a simple test, that creates a loop like the presented below.

   1:  for (TYPE i = 0; i < 10000; i++) {
   2:     TYPE j = i + 1;
   3:     for (TYPE k = j; k > 0; k--) {
   4:        TYPE p = k - j;
   5:     }
   6:  }


I used three ‘types’ of integer (replace the TYPE word above). In first test called StaticTest I used Int32 (an integer), in a second test called VarTest I used the C# var keyword known since .NET 3.0. In the last test called DynamicTest I used a dynamic keyword. I ran this tests on my machine (AMD Turion 64 Laptop with Win7x64 and VS2010 in debug mode) the execution time of the test is presented in table below:

TYPE Average (ms) Total (ms)
Int32 24 242
var 29 297
dynamic 17169 171697


As You can see, there is a big difference in execution time between the dynamic and the rest. The conclusion is – the dynamic is –  and should not be used in code like above in the example for counting operations.

Tip: You cannot use the ‘++’ operator in dynamic types, instead use ‘+=’ like below

   1:  for (dynamic i = 0; i < 10000; i += 1)
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: