BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 4.0+

C# Dynamic Type

It is common for C# applications to interoperate with other languages and frameworks, including dynamic languages such as Python or Ruby. As the typing systems are fundamentally different, C# 4.0 introduces the dynamic type to simplify integration.

What is the Dynamic Type?

Programming languages can be broadly categorised into those that use static typing and those that are dynamically typed. C# is an example of a language that uses static typing. During the build process, all possible uses of all types and their members are checked to ensure that no invalid calls or assignments are made. If there are any problems, they are reported to the user and the compilation fails. This requires that all variables are given a fixed data type. It can lead to higher performance of the final product as little or no run-time type checking is necessary and additional compiler optimisations may be possible.

Dynamically typed languages, such as Python or Ruby, do not have the same restrictions. Often there is no requirement to specify the type of a variable and its type may change during program execution. Dynamically typed languages often allow new types to be created at run-time based upon data not specified in the source code. This additional flexibility is possible because type checks are only performed at run-time. This can lower performance and may produce a greater risk of exceptions whilst the software is executing. However, as more type information is potentially available at run-time, the checking can be more advanced.

In some situations, you will want to integrate statically and dynamically typed languages. To simplify the use of dynamic types with C# code, C#4.0 introduces the dynamic keyword. This allows you to create statically typed objects that bypass compile-time checks. With such objects, you can call any method and read or set any property in your source code without causing build errors. The object's type is only checked for the existence of such members at run-time. This allows C# to work with types that are unknown at compile time, including anonymous types. It also allows improved integration with and other software including COM-based applications.

Using the Dynamic Type

To use the dynamic type in C#, you use the dynamic keyword in place of another type name. In the following sample method, the parameter is declared as the dynamic type. This simple example retrieves a value from the Length property and outputs it to the console. Although the Length property is never declared, the code will still compile as no type checking is undertaken for the dynamic object.

public static void GetFromDynamic(dynamic dyn)
{
    Console.WriteLine(dyn.Length);
}

The GetFromDynamic method defined above can accept an instance of any class or structure that includes a Length property or field. We can demonstrate this by calling the method and passing in a string, as follows:

string test = "Hello, world!";
GetFromDynamic(test);   // Outputs "13"

To enhance the demonstration, we can add a further class that includes a Length property. Add the MeasuringDevice class shown below to the project.

class MeasuringDevice
{
    public string Length { get; set; }
}

We can now call the method and pass a MeasuringDevice object, as in the next example.

MeasuringDevice md = new MeasuringDevice { Length = "Very long" };
GetFromDynamic(md);     // Outputs "Very long"

The key to the dynamic type is that the type checking is disabled until run-time. This can produce problems if the run-time type does not support the members that are called. For example, the following code calls the method using an integer value. If the parameter expected an integer, the code would not compile because the int structure does not include a Length property. As the parameter uses a dynamic type, the code will compile.

int noStaticChecking = 10;
GetFromDynamic(noStaticChecking);

Although no errors are displayed during the build process, the above code is invalid. This will be seen at run-time when a RuntimeBinderException is thrown:

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:
'int' does not contain a definition for 'Length'

Limitations

The above examples show the use of the dynamic type in a purely C# scenario. This is for demonstration purposes only. In most situations it would be inadvisable to use the dynamic type unless you are integrating with a dynamic language or another framework where types are not known at compile time. The removal of static type checks increases the risk of run-time exceptions and prevents the use of some IDE tools, such as Intellisense. It can also decrease the readability and maintainability of your code.

30 May 2010