Skip to content

Instantly share code, notes, and snippets.

@frankhale
Created May 31, 2012 21:22
Show Gist options
  • Save frankhale/2846397 to your computer and use it in GitHub Desktop.
Save frankhale/2846397 to your computer and use it in GitHub Desktop.
This is a .NET 4 Dynamic Dictionary
public class DynamicDictionary : DynamicObject
{
private Dictionary<string, object> _members = new Dictionary<string, object>();
public bool IsEmpty()
{
if (_members.Keys.Count() > 0)
{
return false;
}
return true;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _members.Keys;
}
public IEnumerable<string> GetDynamicMemberNames(string key)
{
if (_members.ContainsKey(key))
{
if (_members[key] is DynamicDictionary)
return (_members[key] as DynamicDictionary)._members.Keys;
}
return null;
}
public Dictionary<string, object> GetDynamicDictionary()
{
return _members;
}
public Dictionary<string, object> GetDynamicDictionary(string key)
{
if (_members.ContainsKey(key))
{
if (_members[key] is DynamicDictionary)
return (_members[key] as DynamicDictionary)._members;
}
return null;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (!_members.ContainsKey(binder.Name))
{
_members.Add(binder.Name, value);
}
else
{
_members[binder.Name] = value;
}
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_members.ContainsKey(binder.Name))
{
result = _members[binder.Name];
}
else
{
result = _members[binder.Name] = new DynamicDictionary();
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment