User Tools

Site Tools


notes:csharp:dynamic

Dynamic Typing in C#

  • Using dynamic types does not generate any compile-time errors, although it may generate runtime errors.
  • At compile-time, an element that is typed as dynamic is assumed to support any operation.
  • Overload resolution occurs at run-time rather than at compile-time.
  • In order to use dynamic typing, reference the Microsoft.CSharp.dll assembly.
  • Dynamic typing is useful when you need to interoperate with dynamic languages and technologies running on the Dynamic Language Runtime (DLR) such as IronPython, COM Iterop, JSON result sets, or DOM.

Two special classes when working with dynamic types:

  • DynamicObject - provides a base class for custom dynamic objects
  • ExpandoObject - enables you to add and delete members of a class instances at run-time and also to set and get values of these members

Example: A simple example of dynamic typing:

dynamic v = "Testing";
Console.WriteLine(v.Length); // 7
 
v = new string[] { "One", "Two" };
Console.WriteLine(v.Length); // 2
 
// The following line compiles although it throws a run-time exception
// of type RuntimeBinderException. It's because the compiler does not 
// check whether the method exists or if it has specified arguments.
v.SomeMethod(8);

Example: Overload a method with an argument of type dynamic. Note that overload resolution occurs at run-time rather than at compile-time:

class Program
{
    static void Main(string[] args)
    {
        MainClass m = new MainClass();
 
        // Invoke MainClass.Test(string str)
        m.Test("Hello there!");  // "Hello there!"
 
        // Invoke MainClass.Test(dynamic)
        m.Test(new TestClass()); // "Hello from TestClass."
    }
}
 
class MainClass
{
    // Two overloads of the Test method.
    public void Test(string str) { Console.WriteLine(str); }
    public void Test(dynamic obj) { obj.Test(); }
}
 
class TestClass
{
    public void Test()
    {
        Console.WriteLine("Hello from TestClass.");
    }
}

Links

notes/csharp/dynamic.txt · Last modified: 2016/10/26 by admin