Smart Reflection with dynamic type in .Net 4.0

A collegue of mine at my current project in NRK showed me how to use the dynamic keyword in C# to perform dynamic casting from a base type to a derived type. I just had to share!

The example starts with the following hierarchy of types:

public class Person{
}

public class Police : Person {
}

public class Fireman : Person{
}

The heart of the matter

Typically, you will have a controller/manager class that calls different workers based on the type of object at hand. In ASP.NET, for example, you may have a controller that will return a different rendering of a view based on the 
type of person to render. In its simplest form, the following 3 functions could form such a controller:
public void Draw(Person p) {
    Console.WriteLine("Drawing a generic person");
}

public void Draw(Police police)    {
    Console.WriteLine("Drawing the police");
}

public void Draw(Fireman fireman) {
    Console.WriteLine("Drawing a firefighter");
}
Easy peasy, you say and proceed to write some test code: 
// Arrange
var people = new List<Person>{
    new Person(),
    new Police(),
    new Fireman()
};
// Act
foreach (Person p in people)
    Draw(p);
Do you see the problem?

…the above code will issue 3 calls to the function that draws the base person type. The other two functions are never called. This is self-explanatory, since the foreach loop defines a Person reference. Using var has the same effect, because it is getting populated from a list of Person objects. The compiler simply does not see the Police or Firemen objects.

Now, if you change the foreach-loop to this:

// Act
foreach (dynamic p in people)
    Draw(p);

(use of the dynamic keyword requires that you add a reference to Microsoft.CSharp and System.Core)

The dynamic keyword is strongly typed, but, the compiler is told that the type of object, p will be determined at runtime, and not during compile time, thus each person object in the list will become a strongly typed police and fireman during runtime, similar to dynamic_cast in c++ (damned near identical if you ask me!)

Concerns

Any type of run-time-type checking will involve reflection in some form or another, however, Microsoft has gone a long way in ensuring that this is second-generation reflection, using a funky named tri-state cache to keep things fast. Another concern, of course, is that you can always cast any type to dynamic without compile-time checking, so you basically want to ensure 100% coverage by unit tests as well as ensure that the unit tests will catch type-mismatches.

Conclusion

Using the dynamic keyword will clean up the code considerably at the cost of having to keep in mind that you wil have no compile time checking of any lines of code that involve the dynamic keyword, so make sure you write those unit tests. Additionally, because this is run-time checking, you should consider other options if you depend on faster code, but for most of your code, the performance impact is non-measurable.

More on dynamic keyword here – Official documentation on MSDN

Dissecting the C# 4.0 Dynamic programming – Good article about the inner workings of dynamic

About digitaldias

Software Engineer during the day, photographer, videographer and gamer in the evening. Also a father of 3. Pedro has a strong passion for technology, and gladly shares his findings with enthusiasm.

View all posts by digitaldias →

2 Comments on “Smart Reflection with dynamic type in .Net 4.0”

    1. Type safety is relative.

      The dynamic cast operator in C# will fail during run-time and can be handled that way. There is no risk of unwanted type conversion, i.e. casting object “house” to one of those persons will not work. It compiles, but the methods provide type safety checks during runtime. This is exactly the point of having a DLR in C#. – The Dynamic Language Runtime is new in .Net 4.0.

      OOP is not always the answer, this type of casting is valuable in an ASP.NET MVC setting where you want a controller to provide the proper view for an object based on its type in a structure where the model and view are clearly separate. Similar patterns, such as MVP and MVVM have clear separations of model and views.

      This type of issues come from the want to decouple view and model, alternatives to this design are IoC container-ish solutions where you preconfigure the connection between view and model, ie. “for this Fireman, use THIS view” – I think MEF extensions target this explicitly.

      Dynamic casting is one alternative to using MEF, particularly useful in ASP.NET MVC.

Leave a Reply to digitaldias Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.