I want to let users iterate through my dictionary without modifying it.
I considertwo solutions:
1.ReadOnlyDictionary -- is there an implementation of that available?
2.Copy the entire dictionary -- what is the most efficient way to copy it ?
Thanks
I want to let users iterate through my dictionary without modifying it.
I considertwo solutions:
1.ReadOnlyDictionary -- is there an implementation of that available?
2.Copy the entire dictionary -- what is the most efficient way to copy it ?
Thanks
Expose an enumeration(IEnumerable).
Edit: Example:
class A : IEnumerable<B>
{
...
public IEnumerator<B> GetEnumerator ( )
{
return _dictionary.GetEnumerator ( );
}
private Dictionary<B> _dictionary;
}
If you only want to provide enumeration, you could expose it as IEnumerable of the Key/Value pair type. However, this obviously restricts some of the read-only tasks that can be performed.
Another option is to write a new class, derived from IDictionary<TKey, TValue> that provides read-only access by mapping those calls through to your real, wrapped dictionary, and throwing exceptions on any modifying calls like Add.
The easiest way to do this would probably be to implement your own collection that is a wrapper around a Dictionary, something along the lines of:
public class ReadOnlyDictionary<T, U>
{
private IDictionary<T, U> BackingStore;
public ReadOnlyDictionary<T, U>(IDictionary<T, U> baseDictionary) {
this.BackingStore = baseDictionary;
}
public U this[T index] { get { return BackingStore[index]; } }
// provide whatever other methods and/or interfaces you need
}
Keep in mind that your values will not be read only with the solutions provided for wrapping a Dictionary with only a property getter; For example:
ReadOnlyDictionary<int, Employee> readOnlyDict = GetDictionaryHoweverYouLike();
ReadOnlyDictionary[5].EmployeeName = "Ooops"
To do that you will also need to wrap your values in a read only wrapper class.