11

i have this

dynamic d = new ExpandoObject();
d.Name = attribute.QualifiedName.Name;

so , i know that d will have a property Name. Now if i don't know the name of the property at compile time , how do i add that property to the dynamic. i found this SO Question

so, there is this complicated concept of call binders etc..which is tough to get in the first place.any simpler way of doing this ?

Community
  • 1
  • 1
ashutosh raina
  • 9,228
  • 12
  • 44
  • 80
  • possible duplicate of [Adding unknown (at design time) properties to an ExpandoObject](http://stackoverflow.com/questions/2974008/adding-unknown-at-design-time-properties-to-an-expandoobject) – nawfal Jul 20 '14 at 06:14

3 Answers3

27
dynamic d = new ExpandoObject();
((IDictionary<string,object>)d)["test"] = 1;
//now you have d.test = 1
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
7

Here is a cleaner way

var myObject = new ExpandoObject() as IDictionary<string, Object>; myObject.Add("Country", "Ireland");

Rustovich
  • 191
  • 1
  • 2
  • 6
4

You can also do like this:-

Dictionary<string,object> coll = new Dictionary<string,object>();
    coll.Add("Prop1","hello");
    coll.Add("Prop2",1);
    System.Dynamic.ExpandoObject obj = dic.Expando();

//You can have this ext method to better help

public static ExpandoObject Expando(this IEnumerable<KeyValuePair<string, object>> 
dictionary)
        {
            var expando = new ExpandoObject();
            var expandoDic = (IDictionary<string, object>)expando;
            foreach (var item in dictionary)
            {
                expandoDic.Add(item);
            }
            return expando;
        }
Ankit Patial
  • 2,597
  • 1
  • 13
  • 12