.Net, Azure and occasionally gamedev

Reflection (3/5) Dynamic keyword

2013/01/11

This is the third post in a series. All posts are short excerpts from my Reflection paper.

C# 4.0 introduced the dynamic keyword.

With the dynamic keyword .Net postpones the type checking until runtime.

While in many cases this doesn't seem like a good idea (especially not when you actually do know the type; after all C# is meant to be statically typed), it comes in handy in more advanced scenarios, since it is a lot less code to write than if it was done with reflection itself.

A simple example where it is useful:

class Calculator
{
    int Add(int a, int b);
}

object calc = new Calculator();
int result = calc.Add(1, 2); // compile error
dynamic calc2 = calc;
int result2 = calc2.Add(1, 2); // actually works

It also opens the possibility to interact with dynamically-typed languages such as Python or Ruby which I think is a really cool feature.

Much like reflection, it will break when you make a typing mistake (dynamically accessing calc.Ad will crash just the same as using reflection ala calc.GetType().GetMethod("Ad")).

Using dynamic is also slightly faster than reflection, so if you have a scenario where both are applicable, dynamic is most likely the way to go as it is less code to write and runs faster.

tagged as C# and Reflection