Search code examples
c#.netdynamic.net-4.0

Adding members to a dynamic object at runtime


I am exploring the DynamicObject model in .NET 4.0. The application is one where an object will be described through some sort of text/xml file, and the program must create an object upon reading that file.

With DynamicObject, we can add members easily, given that we know the name of the member a priori. But, what if we don't even know the name of the member to add? Is there a way to make that dynamic as well?

For example, say I need to create an object with members 'Property1', 'Property2', and another object with 'PropertyA', and 'PropertyB' as described by the text/XML file. How can I create an object dynamically based on this info?

UPDATE I got some ideas from this post: http://www.codeproject.com/KB/cs/dynamicincsharp.aspx

This implementation allows me to do something like the following:

dynamic d = new PFDynamicChannel();
PFCouplings c = ((PFChannel)d).Coupling;
d.NewProperty = "X";

The reason I do not wish to use a dictionary is to make use of TryGetMember, and TrySetMember methods that I can override, within which I can raise events that are essential for the program.

This way, I can inherit from a base class (PFChannel), but I can also add members on the fly. But, my problem is that I will not know the new property name until runtime. And, I actually don't think the dynamic object allows me to add new properties on the fly. If this is the case, how can I make use of ExpandoObject to give me this ability?


Solution

  • If you only need to do that, you should look at ExpandoObject. If you need to do that and still use DynamicObject, you will need to write code to remember property values, basically... which you could potentially do with an embedded ExpandoObject.

    It's not clear to me what you want to do with this object afterwards though - are you sure you need dynamic typing at all? Would a Dictionary<string, object> actually be any worse? It depends what's going to consume the object later basically.