English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# Dynamic Types (Dynamic)

C#4.0 (.NET 4.5)introduced a new type called dynamic, which avoids compile-time type checking. Dynamic types skip type checking at compile time; instead, they resolve types at runtime.

Dynamic type variables are defined using the keyword dynamic.

dynamic MyDynamicVar = 1;

In most cases, the compiler will compile dynamic types to object types. However, the actual type of a dynamic type variable will be resolved at runtime.

dynamic MyDynamicVar = 1;
Console.WriteLine(MyDynamicVar.GetType());
Output:

System.Int32

Dynamic types change their type at runtime based on the assigned value. The following example shows how a dynamic variable changes its type based on the assigned value.

static void Main(string[] args)
{
    dynamic MyDynamicVar = 100;
    Console.WriteLine("Value: {0}, Type: {1MyDynamicVar, MyDynamicVar.GetType());
    MyDynamicVar = "Hello World!!";
    Console.WriteLine("Value: {0}, Type: {1MyDynamicVar, MyDynamicVar.GetType());
    MyDynamicVar = true;
    Console.WriteLine("Value: {0}, Type: {1MyDynamicVar, MyDynamicVar.GetType());
    MyDynamicVar = DateTime.Now;
    Console.WriteLine("Value: {0}, Type: {1MyDynamicVar, MyDynamicVar.GetType());
}
Output:
value:100, type: System.Int32
value: Hello World !!, type: System.String
value: True, type: System.Boolean
value: 01-01-2014, type: System.DateTime

Dynamic type variables will be implicitly converted to other types.

dynamic d1 = 100;
int i = d1;
d1 = "Hello";
string greet = d1;
d1 = DateTime.Now;
DateTime dt = d1;

Methods and parameters

If an object of a class is assigned to a dynamic type, the compiler will not check the correct method and property names of the dynamic type that saves a custom class object. See the following example.

class Program
{
    static void Main(string[] args)
    {
        dynamic stud = new Student();
        stud.DisplayStudentInfo(1, "Bill");// Runtime error, no compile-time error
        stud.DisplayStudentInfo("1");// Runtime error, no compile-time error
        stud.FakeMethod();// Runtime error, no compile-time error
    }
}
public class Student
{
    public void DisplayStudentInfo(int id)
    {
    }
}

In the above example, the C# compiler does not check parameters, parameter types, or they do not exist at all. It validates these at runtime and throws a runtime exception if invalid. Note that dynamic types do not support Visual Studio IntelliSense. Note that dynamic types do not support Visual Studio IntelliSense.

The Dynamic Language Runtime (DLR) API provides the foundational infrastructure for dynamic types in C#.