I've created a dynamic object and set properties and values to it at runtime using ExpandoObject
dynamic parentDynamic = new ExpandoObject();
var parentName = "GroupOne";
((IDictionary<String, Object>)parentDynamic)[parentName] = "default";
Console.WriteLine(parentDynamic.GroupOne);
The Console successfully outputs "default" as expected.
I've also created a child object with multiple properties in the same manner
dynamic childDynamic = new ExpandoObject();
var childProperty1 = "FirstName";
var childProperty2 = "LastName";
var childProperty3 = "Occupation";
((IDictionary<String, Object>)childDynamic)[childProperty1] = "John";
((IDictionary<String, Object>)childDynamic)[childProperty2] = "Smith";
((IDictionary<String, Object>)childDynamic)[childProperty3] = "Plumber";
Console.WriteLine(childDynamic.Occupation);
The Console successfully outputs "Plumber" as expected.
Where I am getting in a jam is when I attempt to add the childDynamic object to the parentDynamic object and give it a name at runtime. Here is my latest failed attempt:
var childName = "ChildOne";
((IDictionary<String, Object>)((IDictionary<String, Object>)parentDynamic)[parentName])[childName] = childDynamic;
Console.Write(parentDynamic.GroupOne.ChildOne.Occupation);
The error I am getting when attempting the assignment is: Unable to cast object of type 'System.String' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
Essentially I would like to be able access parentDynamic.GroupOne.ChildOne.Occupation and get back "Plumber" or parentDynamic.GroupOne.ChildOne.FirstName and get back "John"
Originally I was trying to make my assignments all at once like so
parentDynamic["GroupOne"]["ChildOne"]["Occupation"] = "Plumber"
But I get the error Cannot apply indexing with [] to an expression of type 'System.Dynamic.ExpandoObject' Which is why I went down the path of creating a parent and child object and casting them as Dictionary objects first. Ideally I would like to just do something like the above as it's MUCH simpler.