Search code examples
c#asp.net.netexpandoobject

How to dynamically add properties at runtime to an ExpandoObject?


Below is the code snippet of what I am trying to do.

dynamic model = new ExpandoObject();

foreach (Control control in ConfigData.ActiveForm.Controls)
{
    string controlType = control.GetType().ToString();
    if (controlType == "System.Windows.Forms.TextBox")
    {
        TextBox txtBox = (TextBox)control;
        if (string.IsNullOrEmpty(txtBox.Text))
        {
            MessageBox.Show(txtBox.Name + " Can not be empty");
            return;
        }
        model[txtBox.Name] = txtBox.Text; // this gives error
    }
}

I want to create a property with name of the value that came from txtBox.name.

For example, if the value of textBox.name is "mobileNo", I want to add a property with the name mobileNo to model. How do I do that?


Solution

  • dynamic expando = new ExpandoObject();
    
    // Add properties dynamically to expando
    AddProperty(expando, "Language", "English");
    
    public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
    {
        // ExpandoObject supports IDictionary so we can extend it like this
        var expandoDict = expando as IDictionary<string, object>;
        if (expandoDict.ContainsKey(propertyName))
            expandoDict[propertyName] = propertyValue;
        else
            expandoDict.Add(propertyName, propertyValue);
    }
    

    Thanks to Jay Hilyard and Stephen Teilhet

    source: https://www.oreilly.com/content/building-c-objects-dynamically/