Complete guide to dynamic keyword in C#

The dynamic keyword, a new addition to Microsoft .NET C# 4.0 language, is believed to change the type binding to a variable from compile time to runtime.  This also means that apart from the CLR interpreting the variable type dynamically at runtime, the compiler also has to ignore type-matching of a variable during the compilation process.

This is a paradigm shift from what has been followed since the time of Pascal, C and C++ ages and this article focuses on understanding how dynamic works internally and the best practices to be followed when using dynamic keyword

To understand this, let’s consider a code snippet and analyse it.

  1. classProgram
  2. {
  3.     staticvoid Main(string[] args)
  4.     {
  5.         Program program = newProgram();
  6.         /* Simple Examples
  7.          * Will work on any data type
  8.          * on which + can be applied
  9.          */
  10.         Console.WriteLine(program.Add(2, 3));
  11.         Console.WriteLine(program.Add(2.0d, 3.0d));
  12.         Console.WriteLine(program.Add(“Punit”, “G”));
  13.         /* Will work on any data type
  14.          * on which = can be applied */
  15.         Console.WriteLine(program.Equals(2, 3));
  16.         Console.WriteLine(program.Equals(“Punit”, “G”));
  17.         Console.WriteLine(program.Equals(program, program));
  18.         Console.ReadKey();
  19.     }
  20.     publicdynamic Add(dynamic number, dynamic number2)
  21.     {
  22.         return number + number2;
  23.     }
  24.     publicbool Equals(dynamic o1, dynamic o2)
  25.     {
  26.         return o1 == o2;
  27.     }
  28. }

 

In the above snippet, the Add method takes in 2 dynamic parameters and returns a dynamic value.  This means you can typically pass any data type (that supports a + operation) and expect it to work as normal.  When you pass in a data type that does not support a + operation, the program will throw a RuntimeBinderException

The output of above program as expected is:

5
5
PunitG
False
False
<RuntimeBinderException>

At compile time, CLR converts a dynamic keyword to classes in Microsoft.CSharp.RuntimeBinder and System.Runtime.CompilerServices namespace.  The task of these classes is to invoke DLR at runtime and enable following conversion

 

image

 

So the CLR essentially creates an object of CallSite object.  This CallSite is a runtime-binding handler that creates a dynamic object and allows access its properties and methods.  This access is done using Reflection methods.  This CallSite object is a part of DLR engine and the DLR engine interprets these calls as ‘dynamic invocations’  If the DLR does not know the type of object, it will take effort in finding out.  After discovering the type of object, next is to check if it is a special object (like IronRuby, IronPython, DCOM, COM, etc) or it is C# object.

The CLR takes these DLR objects, passes them through

  • Metadata Analysers -  This analyser detects the type of objects
  • Semantic Analysers – This analyser checks if the intended operations (method calls, properties) can be performed on the object.  If there is any mismatch found in these 2 steps, a runtime exception is thrown.
  • Emitter – The emitter builds an Expression Tree and emits it.  This expression tree is sent back to DLR to build a Object-Cache dictionary.  DLR also calls compile on this expression tree to emit a IL.

On second call, the Object-Cache dictionary is used to skip the re-creation of expression tree for the same object and IL is emitted.   Post IL execution of a dynamic type is same as all other types.

 

Creating new dynamic objects

 

The reason why languages such as IronRuby and IronPython today exists is because .NET language allows you to create your own dynamic types.  You can write your own interpreters in C# or VB.NET and let the community use them as they wish.  Let’s see this in an example where we create a new SampleDynamicObject and use its properties and methods.

 

  1. dynamic sample = newSampleDynamicObject();
  2. // TryGetMember will be invoked sample.Name
  3. Console.WriteLine(sample.Name);
  4. // TryInvokeMember will be invoked PrintDetails
  5. sample.PrintDetails();
  1. publicclassSampleDynamicObject: System.Dynamic.DynamicObject
  2. {
  3.     publicoverridebool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder,
  4.             object[] args, outobject result)
  5.     {
  6.         returnbase.TryInvokeMember(binder, args, out result);
  7.     }
  8.     publicoverridebool TryGetMember(System.Dynamic.GetMemberBinder binder,
  9.             outobject result)
  10.     {
  11.         returnbase.TryGetMember(binder, out result);
  12.     }
  13. }

 

TryInvokeMember is called when any method is called on the dynamic object, while TryGetMember is called when a getter of a property of the dynamic object is called.  Similarly there are other overridable methods that can be implemented.

 

dynamic vs. object

Another aspect of understanding dynamic is to understand how dynamic types are different from System.Object

One variable is typed as object by the compiler and all instance members will be verified as valid by the compiler. The other variable is typed as dynamic and all instance members will be ignored by the compiler and called by the DLR at execution time.

  • Dynamic type can be considered as a special static type that the compiler ignores while compilation which is not the case with System.Object
  • Any operation on object requires type-casting which adds a hit to the performance.  Similarly, defining an object dynamic also involves some extra logic for interpretation.  This extra logic is also referred as Duck Typing
  • An object can be converted to a dynamic type implicitly.  An implicit conversion can be dynamically applied to an expression of type dynamic

 

Limitations of dynamic types

 

The keyword dynamic restricts a lot of functionalities as the type of object is not pre-defined.  Some of the known limitations are

  • Inability to use LINQ, Extension Methods, Lambda expressions
  • Inability to check if type conversions are done correctly
  • Polymorphism can not be fully supported
  • C# language constructs such as using block can not be applied to dynamic types
  • Design principles like Inversion of Control and Dependency Injection are difficult to implement

 

Where best to use dynamic types

 

Some of the areas where, I believe, dynamic types can be used are

  • To leverage runtime type of generic parameters
  • To receive anonymous types
  • To create custom domain objects for data-driven objects
  • To create a cross-language translator (like IronRuby, IronPython, etc) that leverages capabilities of .NET CLR

 

I hope this helps to understand the dynamic keyword and how it differs from System.Object type

Download Source Code

Punit Ganshani

Punit Ganshani, based out of Singapore, is Microsoft C# MVP and specializes in Microsoft technology stack and performance engineering. He is an open-source contributor at Codeplex, CodeProject, DZone MVB, has several apps on Windows Store, author of book, a gadget fan and an evangelist.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInReddit

%d bloggers like this: