Skip to content

Instantly share code, notes, and snippets.

@gkinsman
Created April 1, 2020 11:27
Show Gist options
  • Save gkinsman/432b4bcd9b7cc55c4c5f0cd476e22bb1 to your computer and use it in GitHub Desktop.
Save gkinsman/432b4bcd9b7cc55c4c5f0cd476e22bb1 to your computer and use it in GitHub Desktop.
{
"a": {
"b": {
"c": {
"d": 43
}
}
},
"f": "hello"
}
void Main()
{
dynamic thing = new Expandable();
thing.a.b.c.d = 43;
thing.f = "hello";
string json = JsonConvert.SerializeObject(thing, Newtonsoft.Json.Formatting.Indented);
json.Dump();
}
// Define other methods, classes and namespaces here
public class Expandable : DynamicObject
{
Dictionary<string, object> _members = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!_members.ContainsKey(binder.Name))
_members.Add(binder.Name, new Expandable());
result = _members[binder.Name];
return true;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _members.Keys;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_members[binder.Name] = value;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment