What is the Dynamic Data Type in .net 4.0 with Examples-Tutorial

No.of Views3538
Bookmarked0 times
Downloads 
Votes0
By  pranay rana   On  08 Jan 2011 09:01:46
Tag : CSharp , CSharp4.0
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.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

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

Image Loading

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.

Image Loading

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.

What are the Limitations?

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 step,

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.

Download Sample Project

Download source files -42 kb

Summary

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

 
Sign Up to vote for this article
 
About Author
 
pranay rana
Occupation-CEO
Company-GMind Solusion
Member Type-Expert
Location-India
Joined date-08 Jan 2011
Home Page-http://pranayamr.blogspot.com
Blog Page-http://pranayamr.blogspot.com
Hey, I am Pranay Rana, working as a Senior Software engineer in mid-size company located in ahmedabad. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 4.3 years now. For me def. of programming is : Programming is something that you do once and that get used by multiple for many years You can visit me on my blog - http://pranayamr.blogspot.com/ StackOverFlow - http://stackoverflow.com/users/314488/pranay My CV :- http://careers.stackoverflow.com/pranayamr
 
 
Other popularSectionarticles
    In this article, i will explain how to use the How to use ExpandoObject Class in .NET 4.0.The ExpandoObject class is introduced on .NET Framework 4.0 and inherited using many interfaces.
    Published Date : 16/Apr/2011
    C# 4.0 supports Dynamic Programming by introducing new Dynamic Typed Objects
    Published Date : 26/May/2010
    Dynamic Datatype in C# 4.0 is quit bit familiar to Var Datatype. Deference between Var and Dynamic is VAR initialized on CompileTime and Dynamic initialized On Runtime
    Published Date : 17/May/2010
    In this article I will show how to use the IObserver and IObservable Interfaces in C#. These two interfaces is work with connection to Push based approach on Reactive Framework
    Published Date : 15/Dec/2010
    Through this article, i will introduce in FCL named Tuple which can store n - number of values in it. Yes, you specify the type of each of those variables as generic parameters, and the object will create those values for you
    Published Date : 15/Nov/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top
</