tags:

views:

121

answers:

5

I'm wondering if I can create a Property that returns a Dictionary where a user can not add any new items.

Example:

    private readonly Dictionary<string, IMyObject> _myDictionary;
    public Dictionary<string, IMyObject> MyDictionary
    {
        get { return _myDictionary; }
    }

Now, this should be a "readonly" Dictionary: people using MyDictionary are not allowed to add or remove items. Any way in which this can be done?

+7  A: 

I think that you'll need a class that wraps a Dictionary like the ReadOnlyCollection wraps a List. While you will not find a default class that does this, you'll find an implementation in one of the answers to this question.

The BCL Extras Project also contains such an implementation. It supports the creation of a proxy object which implements IDictionary and can be used in its place.

luvieere
Nice link, thanks :)
leppie
Thanks, I missed that question.
Carra
+1  A: 

Inherit from System.Collections.ObjectModel.KeyedCollection<TKey,TItem>

Override InsertItem and RemoveItem

leppie
A: 

C# doesn't provide a way of doing this exactly the way you suggest, but you could always return a "home-made" immutable dictionary that wraps your myDictionary.

Have a look at this for more info on creating an immutable dictionary.

Does C# have a way of giving me an immutable Dictionary?

Rob Levine
A: 

You'll find a nice tutorial with implemented solution at: http://www.blackwasp.co.uk/ReadOnlyDictionary.aspx

WBR, Dejan

Dejan Stanič
A: 

If the intent of providing this immutable dictionary is to protect your own dictionary, just give them a shallow copy.

public Dictionary<string, IMyObject> MyDictionary 
{ 
    get { return new Dictionary<string, IMyObject>(_myDictionary); } 
} 

Caller may add and remove whatever, but it won't matter for your dictionary.

Of course, the caller still has access to the things in the dictionary and may mutate them. If that's a problem, make a deep copy.

David B