0

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.

2
  • 1
    You can only "add properties" if the object supports it... and the Object type doesn't so it won't work in this case. Commented Oct 13, 2013 at 19:58
  • If this question is related to your earlier question then ExpandoObject is not the way to go. Commented Oct 14, 2013 at 2:55

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think you meant d.key, rather than dictionary.key
@ThomasLevesque: Yup - fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.