Coder Perfect

Adding properties to an ExpandoObject dynamically

Problem

I’d like to add properties to an ExpandoObject dynamically at runtime. So, for example, if I wanted to add a string property called NewProp, I’d write something like this.

var x = new ExpandoObject();
x.AddProperty("NewProp", System.String);

Is this a simple task?

Asked by Craig

Solution #1

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

Answered by Stephen Cleary

Solution #2

As explained here by Filip – http://www.filipekberg.se/2011/10/02/adding-properties-and-methods-to-an-expandoobject-dynamicly/

At runtime, you can also add a method.

x.Add("Shout", new Action(() => { Console.WriteLine("Hellooo!!!"); }));
x.Shout();

Answered by Himanshu Patel

Solution #3

Here’s an example helper class that converts an Object and returns an Expando with all of the object’s public attributes.

public static class dynamicHelper
    {
        public static ExpandoObject convertToExpando(object obj)
        {
            //Get Properties Using Reflections
            BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
            PropertyInfo[] properties = obj.GetType().GetProperties(flags);

            //Add Them to a new Expando
            ExpandoObject expando = new ExpandoObject();
            foreach (PropertyInfo property in properties)
            {
                AddProperty(expando, property.Name, property.GetValue(obj));
            }

            return expando;
        }

        public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
        {
            //Take use of the IDictionary implementation
            var expandoDict = expando as IDictionary<String, object>;
            if (expandoDict.ContainsKey(propertyName))
                expandoDict[propertyName] = propertyValue;
            else
                expandoDict.Add(propertyName, propertyValue);
        }
    }

Usage:

//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);

//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");

Answered by Johannes

Solution #4

This, in my opinion, adds a new property in the desired type without the need to specify a primitive value, as when a property is defined in a class definition.

var x = new ExpandoObject();
x.NewProp = default(string)

Answered by Morteza ebrahim nejad

Post is based on https://stackoverflow.com/questions/4938397/dynamically-adding-properties-to-an-expandoobject