C# Dynamic Type Tutorial

In this tutorial we learn about the dynamic type and how its type resolution is done at runtime instead of compilation time.

We cover the DLR (dynamic language runtime), the GetType() method, dynamic members and method parameters.

What are the two types

Programming languages are divided into two types, statically-typed and dynamically-typed.

  • Statically-typed, such as C# or Java
  • Dynamically-typed, such as Python or Javascript

In static languages, the resolution of types is done at compile time, before the program is run.

For example, if we try to access a method that’s not defined in a class, the compiler will tell us before the program is run that the method wasn’t found. The program can’t be compiled or run while there are errors.

In dynamic languages, the resolution is done at runtime, while the program is running.

For example, if we try to access a method that’s not defined in a class, we’ll only know that the method wasn’t found while the program is running. Other parts of the script may still run while there are errors.

The DLR (Dynamic Language Runtime)

We’re already familiar with CLR, the common language runtime. As a quick recap, CLR translates our code into an intermediate language (IL Code) before translating it into machine code.

In .NET Framework 4 Microsoft added DLR, the dynamic language runtime that sits on top of CLR and provides us with dynamic capabilities.

The Dynamic type

The dynamic type will tell the compiler that a variable’s type can change during runtime, or that the type will not be known until runtime.

The compiler will skip the compile time checks on a dynamic type.

A dynamic type can be defined using the dynamic keyword.

Syntax:
 dynamic variable_name = any_value;
Example:
using System;

namespace Dynamics
{
    class Program
    {
        static void Main()
        {
            dynamic someValue = 10;
            Console.WriteLine(someValue);

            someValue = 3.14f;
            Console.WriteLine(someValue);

            someValue = "Hello World";
            Console.WriteLine(someValue);

            Console.ReadLine();
        }
    }
}

Normally we would have to define 3 variables, each of its own type, to hold the values in the above example.

In most cases the compiler will compile a dynamic type into an object type.

Example:
dynamic someValue = 1;

Will be compiled as:

Example:
object someValue = 1;

The GetType() method

We can get the actual type of he dynamic at runtime by using the GetType() method.

Example:
using System;

namespace Dynamics
{
    class Program
    {
        static void Main()
        {
            dynamic someValue = 10;
            Console.WriteLine("Value: {0} Type: {1}", someValue, someValue.GetType().ToString());

            someValue = 3.14f;
            Console.WriteLine("Value: {0} Type: {1}", someValue, someValue.GetType().ToString());

            someValue = "Hello World";
            Console.WriteLine("Value: {0} Type: {1}", someValue, someValue.GetType().ToString());

            Console.ReadLine();
        }
    }
}

Dynamic properties and methods

If a class is assigned to a dynamic type, the compiler will not check at compile time for the correct properties and methods.

Example:
using System;

namespace Dynamics
{
    class Program
    {
        static void Main()
        {
            dynamic book = new Books();

            book.id = 1;
            book.name = "Learn C#";
            book.LogToConsole();

            book.NonExistingMethod(); // no compiler error
        }
    }

    public class Books
    {
        public int id { get; set; }
        public string name { get; set; }

        public void LogToConsole()
        {
            Console.WriteLine("Book ID: {0}", id);
            Console.WriteLine("Book Name: {0}", name);
        }
    }
}

In the example above, we instantiate a Books object as a dynamic type. We use the object as we normally would, but when we try to call a method that doesn’t exist, the compiler allows it.

When you run the application, it executes the working code and then raises an error when it gets to the method that doesn’t exist.

Dynamic method parameter

We can have dynamic input parameters in our methods that will accept any value at runtime.

Example:
using System;

namespace Dynamics
{
    class Program
    {
        static void Main()
        {
            LogToConsole(10);
            LogToConsole(3.14f);
            LogToConsole("Hello World");

            Console.ReadLine();
        }

        static void LogToConsole(dynamic val)
        {
            Console.WriteLine(val);
        }
    }
}

Summary: Points to remember

  • A dynamic type is a type that’s unknown until runtime. The compiler will skip compile time checks on it.
  • We use the GetType() function to get the actual type of a dynamic.
  • When a class is instantiated as dynamic, the class’s attributes and methods will not be checked during runtime.
  • Dynamic parameters in functions and methods will accept any value at runtime.