Dynamic Programming In .NET 4.0

Introduction

C# 4.0 supports dynamic programming by introducing new dynamic-typed objects. The type of these objects is resolved at run-time instead of at compile-time. The keyword tells the compiler that everything to do with the object declared as dynamic should be done dynamically at the run-time using Dynamic Language Runtime(DLR).

The main advantage of this dynamic programming is it provides more flexibility to developers.

Example

using System;
class Program
{
    static void Main(string[] args)
    {
        dynamic num = GetNum();
        dynamic str = GetString();

        Console.WriteLine("Your number is " + num);
        Console.WriteLine("Your string is " + str);
        Console.Read();
    }
    private static string GetString()
    {
        return "Welcome";
    }
    private static int GetNum()
    {
        return 1;
    }
}

Note. We use the var keyword, but the main difference between both is var is resolved at compile time, and dynamic is resolved at runtime.


Similar Articles