Here is the implementation that I use for all those who need a piece ready for sending
public class DictionaryReadOnly<TKey, TValue> : IDictionary<TKey, TValue>
{
#region Private Members
private IDictionary<TKey, TValue> _item;
private bool _throwOnWritableAction = false;
#endregion
#region Constructors
public DictionaryReadOnly(IDictionary<TKey, TValue> items)
{
_throwOnWritableAction = true;
_item = items;
}
public DictionaryReadOnly(IDictionary<TKey, TValue> items, bool throwOnWritableAction)
{
_throwOnWritableAction = throwOnWritableAction;
_item = items;
}
#endregion
#region IDictionary<TKey,TValue> Members
public int Count
{
get { return _item.Count; }
}
public bool ContainsKey(TKey key)
{
return _item.ContainsKey(key);
}
public TValue this[TKey key]
{
get { return _item[key]; }
set
{
CheckAndThrow("Set");
}
}
public ICollection<TKey> Keys
{
get { return _item.Keys; }
}
public void Add(TKey key, TValue value)
{
CheckAndThrow("Add");
}
public bool Remove(TKey key)
{
CheckAndThrow("Remove");
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
if (_item.ContainsKey(key))
{
value = _item[key];
return true;
}
return false;
}
public ICollection<TValue> Values
{
get { return _item.Values; }
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add(KeyValuePair<TKey, TValue> item)
{
CheckAndThrow("Add");
}
public void Clear()
{
CheckAndThrow("Clear");
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _item.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
this._item.CopyTo(array, arrayIndex);
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
CheckAndThrow("Remove");
return false;
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _item.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return _item.GetEnumerator();
}
#endregion
void CheckAndThrow(string action)
{
if (_throwOnWritableAction)
throw new InvalidOperationException("Can not perform action : " + action + " on this read-only collection.");
}
}
source
share