Dynamic Type in C# 4.0


Dynamic is a new type introduced in c# 4.0.Dynamic types are declared with the dynamic keyword. The objects of type Dynamic are not type checked at compile time. It behaves like type Object in most cases .Object of any type can be assigned to a variable of Dynamic type .Variable of Dynamic type can get its value even from HTML Document Object Model (DOM) or COM API. If the code is not valid, errors are caught at run time not at compile time.

C# was until now a statically bound language. This means that if the compiler couldn't find the method for an object to bind to then it will throw compilation error.

We declare at compile-time the type to be dynamic, but at run-time we get a strongly typed object.

Dynamic objects expose members such as properties and methods at run time, instead of compile time. If you try to access members of a Dynamic type in visual studio IDE you will get the message "The operation will be resolved at runtime".

1.gif 

Difference between Object, Var and Dynamic type

If we execute the following code 

dynamic dyn = 0;
object obj = 0;
var var = 0;
System.Console.WriteLine(dyn.GetType());
System.Console.WriteLine(obj.GetType());
System.Console.WriteLine(var.GetType());

We will get the runtime types of all the Object ,Dynamic and var variables as Sytem.Int32 .But the type of var variable is available at compile time as well.

But now if we add the following two statements the second statement will give compile time error  because the expression is type checked at compile time while the first statement compiles successfully because expressions of dynamic type are not type checked at compile time and the var type variable is assigned the appropriate datatype at compile time itself.

dyn = dyn + 1;
obj = obj + 1;
var = var + 1;
 
If we execute the below program

class Dynamic
{
    static void Main(string[] args)
    {
        dynamic dyn;
        string str = "Dynamic type test.String";
        StringBuilder sb = new StringBuilder();
        sb.Append("Dynamic type test.StringBuilder");
        dyn = str;
        DynamicFunction(dyn);//This will call the first function because at run time the dynamic type is of string type
        dyn = sb;
        DynamicFunction(dyn);////This will call the first function because at run time the dynamic type is of string builder type
        Console.Read();
    }
    public static void DynamicFunction(string s)
    {
        Console.WriteLine(s);
    }
    public static void DynamicFunction(StringBuilder sb)
    {
        Console.WriteLine(sb.ToString());
    }
}

We will get the output as shown below:

2.gif
 
To conclude Dynamic Type is a nice feature when it comes to interoperatibility and .NET usage with other Dynamic languages. However Dynamic type also makes it the responsibility of the developer for the correct usage of the calls.

Up Next
    Ebook Download
    View all
    Learn
    View all