C# 4.0 Dynamic

one of the core functionalities of .NET 4.0 is its support for Dynamic languages. this is done primarly through the Dynamic Language Runtime (DLR) on top of the CLR. this post shows some of the usages of dynamic in C# 4.0.

consider the following class:
public class Sample
public static int Add(int x, int y)
return x + y;

public static float Add(float x, float y)
return x + y;

public static double Add(double x, double y)
return x + y;

this shows a very familier pattern where we use overloading to support multiple versions of the Add method. Now normally in order to invoke the many overloads of the Add method, you would write something like the below code:

int x = 3;
int y = 4;
int z = Sample.Add(x, y);

float x1 = 3f;
float y1 = 4f;
float z1 = Sample.Add(x1, y1);

long x2 = 3L;
long y2 = 4L;
long z2 = Sample.Add(x2, y2);

the problem with this pattern is that we had to define parameters with appropriate types for each method overload. Now in C# 4.0 we can write much more elegant code as follows:

dynamic x3 = 1.2;
dynamic y3 = 1.55;
dynamic z3 = Sample.Add(x3, y3);

using the dynamic keyword, it is left to the runtime to determine the overload of method we would like to call; in this case the decimal-typed overload. for example changing the values of x3 and y3 to integers would call the integer-typed overloads as follows:

dynamic x3 = 1;
dynamic y3 = 1;
dynamic z3 = Sample.Add(x3, y3);

Now lets take another – even more impressive – example. Consider the below class

public class Wrapper
public void DoAction1()
//any stuff

Normally, we do the following to invoke method DoAction1:

Wrapper wrapper = new Wrapper();

ok so now what if you do not know about the method at design time? the direct answer would be reflection. true, but that’s not pretty at all. Using dynamic you can use the following code:

//instead of reflection
dynamic dynWrapper = new Wrapper();
dynamic val = dynWrapper.DoAction2();

by initializing the class to a variable of type dynamic, we can now call methods that will be verified at runtime only. for instance the above code will compile even though DoAction2 does not exist! of course this code will fail at runtime but the idea is that at design time you might not know about the methods of class dynWrapper but you know that at runtime the method will be available…

That’s just a first look at C# 4.0 dynamic keyword.


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 )

Connecting to %s