0

I was trying to create objects at runtime. We have .net framework provided classes like DynamicObject and ExpandoObject. Is it possible to create a dynamic object like this

dynamic obj = new expandoObject();
obj["propName1"] = "name"; //string type
obj["propName2"] = 24; //int type

I dont know the property names until runtime. Is it possible to do this way?

3
  • 1
    Isn't a dictionary enough? Commented Feb 4, 2014 at 18:44
  • 1
    If you don't know the property names until runtime, how do you intend to read the values afterwards? As @BlackBear says, why can't you use a dictionary? Commented Feb 4, 2014 at 18:46
  • Have a look here: stackoverflow.com/questions/14420427/… Commented Feb 4, 2014 at 18:51

1 Answer 1

4

Well, two things.

First, yes, you can stuff values into the ExpandoObject object using "property names" contained in strings, because it implements IDictionary<string, object>, so you can do it like this:

void Main()
{
    dynamic obj = new ExpandoObject();
    var dict = (IDictionary<string, object>)obj;
    dict["propName1"] = "test";
    dict["propName2"] = 24;

    Debug.WriteLine("propName1=" + (object)obj.propName1);
    Debug.WriteLine("propName2=" + (object)obj.propName2);
}

Notice how I use the property syntax to retrieve the values there. Unfortunately, dynamic is like a virus and propagates, and Debug.WriteLine is none too happy about dynamic values, so I had to cast to object there.

However, and this is the second thing, if you don't know the property names until runtime, those last two lines there won't appear anywhere in your program. The only way to retrieve the values is again to cast it to a dictionary.

So you're better off just using a dictionary to begin with:

void Main()
{
    var obj = new Dictionary<string, object>();
    obj["propName1"] = "name";
    obj["propName2"] = 24;

    Debug.WriteLine("propName1=" + obj["propName1"]);
    Debug.WriteLine("propName2=" + obj["propName2"]);
}
Sign up to request clarification or add additional context in comments.

Comments

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.