Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

dynamic keyword - Represents an object whose operations will be resolved at runtime

5.00/5 (3 votes)
15 May 2011CPOL 18K  
dynamic keyword - Represents an object whose operations will be resolved at runtime
C#4.0 introduces a new type, dynamic.It is treated as System.Object, but in addition, any member access (method call, field, property, or indexer access, or a delegate invocation) or application of an operator on a value of such type is permitted without any type checking, and its resolution is postponed until run-time.

This is the one of the best example uses of dynamic:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    public class Colour
    {
    }
    public class Red : Colour
    {
    }
    public class Green : Colour
    {
    }
    class Program
    {
        static void Main(string[] args)
        {
            Colour color = null;
            color = new Red();
            GetColour(color);
            color = new Green();
            GetColour(color);
            Console.ReadLine();
        }        

        static void GetColour(Colour color)
        {
            /* avoiding this lines
            if (color is Red)
            {
                Fill((Red)color);
            }
            if (color is Green)
            {
                Fill((Green)color);
            }
             * */
            //type checking has to be done at runtime.
            dynamic dynColour = color;
            Fill(dynColour);
        }
        static void Fill(Red red)
        {
            Console.WriteLine("RED");
        }
        static void Fill(Green green)
        {
            Console.WriteLine("GREEN");
        }
    }
}

VB
Output
RED
GREEN


The role of the C# compiler here is simply to package up the necessary information about “what is being done to dynColour” so that the runtime can pick it up and determine what the exact meaning of it is given an actual object dynColour. Think of it as deferring part of the compiler’s job to runtime.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)