Pranay Rana: Dynamic Types and Use of it

Wednesday, January 5, 2011

Dynamic Types and Use of it

Download Code
What is Dynamic Types ?

Dynamic types are new feature of C# 4.0, which can be defined easily by using the keyword dynamic. Dynamic types are not strongly typed i.e not bound with any specific data type, so they are different from implicit data type defined using var which can bind with any data type when we define. Like any other type Dynamic types also have base class System.Object.

How Dynamic types works ?

Syntax:
dynamic variable = value;

Let’s see the below example to understand dynamic types in more detail.
static void Main(string[] args)
{
Step 1
Declare a dynamic variable named dc_variable and assigned integer value 5, than print its type and value of the variable
dynamic dc_variable = 5;
Console.WriteLine("Type = " + dc_variable.GetType() + " Value=" + dc_variable);

Step 2
Change the value of the declared variable to boolean type and assign false to it, then print its type and value.
dc_variable = false;
Console.WriteLine("Type = " + dc_variable.GetType() + " Value=" + dc_variable);
Console.ReadLine();
}
When you compile the above code, the compiler will not give any error because the variable is of dynamic type. Since you can change it value at runtime to any other type, so, it is not strongly typed like other variable type of C#.
After compiling when you run the code you will get below output


Above example proves that the dynamic type variable gets evaluated at runtime not at compile time.

Point To Remember

There is no intelligence support for the dynamic types in Visual Studio which we find with other type, or, user defined types.
As shown in above image you can see that the variable is dynamic type and its type gets resolved at runtime.
Because Dynamic type values get resolved at runtime not at compile type you can attach any method with the variable as below.
dc_variable.toDisplayType();
But remember if there is no method like this fond with dynamic variable then it would result in RuntimeBinderException at runtime. So to avoid this problem you can use try catch block and catch exception at runtime
try
{
  dc_variable.toDisplayType();
}
catch(RuntimeBinderException ex)
{
  //code to handle exception
}
So beware with the name of the method we are calling upper case or lower case otherwise it throws exception at runtime.

Limitation

1. Dynamic types are not compatible with anonymous method and lambda expression. So the code like below is not possible
var a = ( dc_variable => x= x+1 );
2. Dynamic types are not able to use most of the methods of Linq API.
3. Linq queries cannot use Dynamic types to get data.
    So, following is not possible with the dynamic variable
var list = form a in dc_variable;

Where dynamic variable are more usefull ?

Dynamic types are more useful when we use Reflection i.e. late binding or COM component in application. Basically it minimizes the amount of code and also makes the code under stable.
Here in this post I am just going to discuss how to use dynamic types when developing application using Refection.
To understand how we use dynamic types when coding using reflection feature go through following steps

Step 1
Create one class Helloworld
public class HelloWorld
{
        public void showMessage()
        {
            Console.WriteLine("Hello World");
        }
        public void showMessageWithDetails(string name, string message)
        {
            Console.WriteLine("Hello " + name + "your message is " + message);
        }
}
As you see Class has two methods (showMessage without parameter,showMessageWithDetails with parameter) which simply display message on console.

Stpe 2
I am going to call the method(s) of the Hello World class using reflection.
public void DisplayMessageUsingReflection(Assembly asm)
{
            try
            {
                //get type meta data 
                Type helloWorld = asm.GetType("ShowMessages.HelloWorld");
                //create object 
                object obj = Activator.CreateInstance(helloWorld);
                //get the methodinfo
                MethodInfo mi = helloWorld.GetMethod("showMessage");
                //call method
                mi.Invoke(obj, null);
            }
            catch (Exception ex)
            { }
}
Above method takes assembly as argument. Create object of the Hello World class and then call the showMessage method.

Stpe 3
Now we call same method by using dynamic types
public void DisplayMessageUsingDynamic(Assembly asm)
 {
            try
            {
                //get tye meta data 
                Type helloWorld = asm.GetType("ShowMessages.HelloWorld");
                //create object 
                dynamic obj = Activator.CreateInstance(helloWorld);
                //call method
                obj.showMessage();
            }
            catch (Exception ex)
            { }
 }
By using dynamic types we can easily call the method and it’s also minimizing the amount of the code to be written.
Now I am going to call showMessageWithDetails method of Hello World class, which is having set of parameter.

Step 4
First calling method with the Normal Reflection code
public void DisplayMessageUsingReflectionWithParamete(Assembly asm)
{
            try
            {
                //get type meta data 
                Type helloWorld = asm.GetType("ShowMessages.HelloWorld");
                //create object 
                object obj = Activator.CreateInstance(helloWorld);
                //get the methodinfo
                MethodInfo mi = helloWorld.GetMethod("showMessageWithDetails");
                //call method and passing parameter
                object[] args = { "pranay", "test message for you" };
                mi.Invoke(obj, args);
            }
            catch (Exception ex)
            { }
}

To call method with the parameter we need to create array of the object which get passed to the method when we call the method.

Step 5
Now calling method using dynamic type
public void DisplayMessageUsingDynamicWithParameter(Assembly asm)
 {
            try
            {
                //get type meta data 
                Type helloWorld = asm.GetType("ShowMessages.HelloWorld");
                //create object 
                dynamic obj = Activator.CreateInstance(helloWorld);
                //call method
                obj.showMessageWithDetails("pranay", "test message for you");
            }
            catch (Exception ex)
            { }
 }

When calling with dynamic there is no need to create any extra array of object. Just have to pass parameter as we do in normal method call.

Summary
Dynamic types are more help full we do late binding at runtime. It’s make code easy and understandable.

2 comments:

  1. My best to you and your Dear Jackie as you continue to tear down the barriers you encounter
    Has understood not absolutely well. this excite
    [url=http://yodideg.qualityonlinenetwork.com/page-58.html]1996 thunderbird headlights[/url]

    Good Luck,

    ReplyDelete
  2. I am generally just an observer when it comes to blogs, but this actually made me want to leave a comment. Wonderful work!

    ReplyDelete