The dynamic Keyword and Late Binding

C# is a statically typed language that means we cannot assign object of one type to another.For example

If we have created object of string like
var Data = “string”;
so, we cannot assign int value to Data object using
Data = 1;

If you try to do above conversion then compiler will through the error saying that “Cannot implicitly convert type ‘int’ to ‘string'”.
This we can resolve using the dynamic keyword.
dynamic Data = “string”;
Data = 1;

This time compiler will not through any error because dynamic “represents an object whose operations will be resolved at runtime”.

The main use of dynamic object is to create an “ExpandoObject” object.
Expando Object means you can create properties for that object as per your need and use it in your program.

For example:
Data = new ExpandoObject();
Data.Name = “WhiteX”;
Data.Type = “Learning”;
Console.WriteLine(“{0} – {1}”, Data.Name, Data.Type);

The complete code for above example is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

namespace Dynamic
{
    class Program
    {
        static void Main(string[] args)
        {

            dynamic Data = "string";
            Console.WriteLine(Data);
            Data = 1;
            Console.WriteLine(Data);

            Data = new ExpandoObject();
            Data.Name = "WhiteX";
            Data.Type = "Learning";
            Console.WriteLine("{0} - {1}", Data.Name, Data.Type);

        }
    }
}

Note*: Please use this dynamic keyword feature when you really need it otherwise go with static type of object because if you do any mistake it will be catch at runtime only.

Advertisements

#dynamic-keyword-or-late-binding