cody wrote:
I know I can use ArrayList.ReadOnly() to create a readonly version of it,
but how can I achive a similar thing with a generic collection of .NET 2.0?
Implement a proxy for the relevant collection, which throw's on mutation.
Here is an example on the .NET1.1 IDictionary, I haven't changed to
..NET2 yet -- you should be able to write one for IDictionary<> in .NET2
yourself.
using System.Collections;
class Immutable: Exception
{ public Immutable(): base("Attempt to change immutable object") {} }
/// <summary>
/// Provide immutable access to a dictionary.
/// </summary>
/// <remarks>
/// In JAVA, iterators, as well as the key- and value- parts, of a
dictionary
/// (called Map) allows mutation, so in JAVA a much more elaborate proxying
/// is required.
/// </remarks>
class ImmutableIDictionary: IDictionary
{
protected readonly IDictionary proxied;
public ImmutableIDictionary(IDictionary proxied) {
if ( proxied == null )
throw new ArgumentException(
"Cannot proxy uninstantiated IDictionary", "proxied");
this.proxied = proxied;
}
#region IDictionary Members
public bool IsReadOnly { get { return true; } }
public IDictionaryEnumerator GetEnumerator()
{ return proxied.GetEnumerator(); }
public object this[object key]
{ get { return proxied[key]; } set { throw new Immutable(); } }
public void Remove(object key) { throw new Immutable(); }
public bool Contains(object key) { return proxied.Contains(key); }
public void Clear() { throw new Immutable(); }
public ICollection Values { get { return proxied.Values; } }
public void Add(object key, object value) { throw new Immutable(); }
public ICollection Keys { get { return proxied.Keys; } }
public bool IsFixedSize { get { return true; } }
#endregion
#region ICollection Members
public bool IsSynchronized { get { return proxied.IsSynchronized; } }
public int Count { get { return proxied.Count; } }
public void CopyTo(Array array, int index) { proxied.CopyTo(array,
index); }
public object SyncRoot { get { return proxied.SyncRoot; } }
#endregion
#region IEnumerable Members
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
IEnumerable e = proxied;
return e.GetEnumerator();
}
#endregion
}
--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music:
http://ungdomshus.nu <=-