Dynamic type is a new type in C# 4.0. Dynamic type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython and javascript, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. However, if the code is not valid, errors are caught at run time. In another word, an exception will occur.

When you use the dynamic keyword, you are invoking the new Dynamic Language Runtime libraries (DLR) in the .NET framework.  The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. Dynamic languages can identify the type of an object at run time instead of compile time, whereas in statically typed languages such as C# when you use option explicit on, you must specify object types at design time. Examples of dynamic languages are Lisp, JavaScript, PHP, Smalltalk, Ruby, Python, ColdFusion, Cobra, and now C#.

Here are main advantages of using DLR

  • Simplifies Porting Dynamic Languages to the .NET Framework
  • Enables Dynamic Features in Statically Typed Languages
  • Provides Future Benefits of the DLR and .NET Framework
  • Enables Sharing of Libraries and Objects
  • Provides Fast Dynamic Dispatch and Invocation

Dynamic Language Runtime Architecture Overview http://jack-fx.com

Now, let’s back to the dynamic type in C#. Here is an example.

we have a class named MyTestClass

   1: class MyTestClass

   2: {

   3:     public MyTestClass()

   4:     {

   5:         Console.WriteLine("constractor with no parameter");

   6:     }

   7:     public MyTestClass(int v)

   8:     {

   9:         Console.WriteLine("constractor with parameter:{0}", v);

  10:     }

  11:  

  12:     public void TestMethod1(int i)

  13:     {

  14:         Console.WriteLine("Test method with parameter:{0}", i);

  15:     }

  16: }

And we can call it like this

   1: dynamic myInstance = new MyTestClass();

   2: myInstance.TestMethod1(101);

It is exactly like the non-dynamic type, but we can use it in this way.

   1: dynamic myInstance = new MyTestClass();

   2: myInstance.nonexistentMethod();

Yes, the nonexistentMethod method doesn’t exist. And you will find there will be no error occurred when compiled. But if you run it, you will get an exception like this

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ‘C4Test.MyTestClass’ does not contain a definition for ‘nonexistentMethod’

This is the dynamic type in C#, give you the flexibility, and do everything at runtime.