Skip to content

Instantly share code, notes, and snippets.

@kamyar1979
Created August 7, 2012 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamyar1979/3284026 to your computer and use it in GitHub Desktop.
Save kamyar1979/3284026 to your computer and use it in GitHub Desktop.
The famous, widely needed, DynamicDictionary class.
namespace System.Dynamic
{
using System;
using System.Collections.Generic;
public class DynamicDictionary : DynamicObject
{
private Dictionary<string, object> items;
public DynamicDictionary()
{
this.items = new Dictionary<string, object>();
}
public void Add(string key, object value)
{
items.Add(key, value);
}
public bool ContainsKey(string key)
{
return items.ContainsKey(key);
}
public bool Remove(string key)
{
return items.Remove(key);
}
public object this[string key]
{
get
{
return items[key];
}
set
{
items[key] = value;
}
}
public void Clear()
{
items.Clear();
}
public int Count
{
get { return items.Count; }
}
public bool IsReadOnly
{
get { return ((ICollection<KeyValuePair<string, object>>)items).IsReadOnly; }
}
public bool Remove(KeyValuePair<string, object> item)
{
return ((ICollection<KeyValuePair<string, object>>)items).Remove(item);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return items.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (items.ContainsKey(binder.Name))
{
items[binder.Name] = value;
return true;
}
return false;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
var iter= items.GetEnumerator();
while (iter.MoveNext())
{
yield return iter.Current.Key;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment