Peter
Peter

Reputation: 11920

How to dynamically build properties on an object

It appears, the new "dynamic" object let's you create properties on the fly:

dynamic v = new object();
v.x = "a";
v.y = "b";
...

I am wondering if there is an easy way to programatically create properties. For example, let's say my properties are stored in a list as follows:

Tuple<string, string>[] list = new Tuple<string, string>[] {
  new Tuple<string, string>("x", "a"),
  new Tuple<string, string>("y", "b"),
};

I would like to iterate through this list and achieve the same result as we did earlier.

dynamic v = new object();
foreach (Tuple<string, string> keyValue in list) {
    // somehow create a property on v that is named keyValue.Item1 and has a value KeyValue.Item2            
}

I am wondering if this is even possible.

Upvotes: 0

Views: 81

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503140

Your initial code is incorrect. It will fail at execution time. If you use ExpandoObject instead, then it will work - and then you can do it programmatically as well, using the fact that ExpandoObject implements IDictionary<string, object>. It implements it with explicit interface implementation, however, so you need to have an expression of that type first. For example:

dynamic d = new ExpandoObject();
IDictionary<string, object> dictionary = d;
dictionary["key"] = "value";
Console.WriteLine(d.key); // Prints "value"

Or for your example:

dynamic v = new ExpandoObject();
IDictionary<string, object> dictionary = v;
foreach (Tuple<string, string> keyValue in list)
{
    dictionary[keyValue.Item1] = keyValue.Item2;
}

I'd personally use KeyValuePair rather than Tuple for this by the way - because that's what you've got here.

Upvotes: 5

Related Questions