'Dynamically Add C# Properties at Runtime

I know there are some questions that address this, but the answers usually follow along the lines of recommending a Dictionary or Collection of parameters, which doesn't work in my situation.

I am using a library that works through reflection to do lots of clever things with objects with properties. This works with defined classes, as well as dynamic classes. I need to take this one step further and do something along these lines:

public static object GetDynamicObject(Dictionary<string,object> properties) {
    var myObject = new object();
    foreach (var property in properties) {
        //This next line obviously doesn't work... 
        myObject.AddProperty(property.Key,property.Value);
    }
    return myObject;
}

public void Main() {
    var properties = new Dictionary<string,object>();
    properties.Add("Property1",aCustomClassInstance);
    properties.Add("Property2","TestString2");

    var myObject = GetDynamicObject(properties);

    //Then use them like this (or rather the plug in uses them through reflection)
    var customClass = myObject.Property1;
    var myString = myObject.Property2;

}

The library works fine with a dynamic variable type, with properties assigned manually. However I don't know how many or what properties will be added beforehand.



Solution 1:[1]

Thanks @Clint for the great answer:

Just wanted to highlight how easy it was to solve this using the Expando Object:

var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
foreach (var property in properties) {
    dynamicObject.Add(property.Key,property.Value);
}      

Solution 2:[2]

you could deserialize your json string into a dictionary and then add new properties then serialize it.

var jsonString = @"{}";

var jsonDoc = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);

jsonDoc.Add("Name", "Khurshid Ali");

Console.WriteLine(JsonSerializer.Serialize(jsonDoc));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Morteza Jalambadani
Solution 2 Morteza Jalambadani