Search code examples
c#dynamiclate-bindingexpandoobjectdynamicobject

When/Why should I use late-binding? (DynamicObject and ExpandoObject)


While DynamicObjects and ExpandoObjects (Differences between ExpandoObject, DynamicObject and dynamic) sound quite useful at first, i did never actually use them. It feels like late-binding is quite unsafe/unstable since it might throw errors at run-time which could've otherwise been avoided. In general MSDN points out several advantages of early-binding and suggests not to use late-binding at all if possible (https://msdn.microsoft.com/en-us/library/0tcf61s1.aspx).

Since I was never in a situation that i could not solve without late-binding and since it seems to be considered 'bad style', I would like to know if there are there situations that actually require the use of late-binding. Do you have any examples where you used late-binding (in particular the DynamicObject or ExpandoObject) and had a good reason for this design choice exept for it being "easy to code"?


Solution

  • Most of the times it's better to stay away from using dynamic and adhere to a type-safe programming style.

    But there are situations when using dynamic could make your life better, or even more, could allow you to do really cool stuff that would be impossible to do without dynamic.

    ExpandoObject

    Consider the following example (without using ExpandoObject):

    Dictionary<String, object> info = new Dictionary<string, object>();
    Dictionary<String, object> person = new Dictionary<string,object>();
    info["Person"] = person;
    person["Name"] = "John";
    person["Surname"] = "Smith";
    

    Now using ExpandoObject:

    dynamic info = new ExpandoObject();
    info.Person = new ExpandoObject();
    info.Person.Name = "John";
    info.Person.Surname = "Smith";
    

    Isn't this better? You could use ExpandoObject instead of dictionary whenever you need some kind of property bag to manipulate big hierarchies of objects. But if you have a plain small dictionary, probably, it's better to stick to the dictionary - it's clearer and there is no performance overhead.

    DynamicObject

    Now imagine that you have huge hierarchy of objects (say, coming from JSON). You could create custom DynamicObject to deserialize JSON into dynamic object easily, see example here. You can do a lot of more cool things via DynamicObject!


    Plus, DLR (and dynamic support in C#) allows you, for example, to execute dynamic languages (e.g.IronRuby) from C# context.

    As you see, dynamic support in C# is a very powerful concept, but must be used only whenever appropriate.