C# – dynamic type can be useful

I am not a big fan of dynamic type in C#, however there are certain situations in which it can be handy. Let’s assume that we have following piece of code (which I encounter quite often at my work)

As you can see we have to convert DTO objects into “normal” objects using some kind of converter. This is not a problematic when you can use some auto-mappings libraries (Automapper,FastMapper) however I am not allowed to do that in a company I work for. So the question is how to write WeaponConverter.Convert method in some elegant way. The obvious way (but definitely not elegant) is just to use lots of “if” statements

But this is really ugly, much better idea (at least from my point of view) is to leverage dynamic keyword introduced in .NET 4. Thanks to it our Convert method can be reduced to this

Source code for this post can be found here

C# – dynamic type can be useful