I’ve a question.
I most recently changed one of my IDictionary to a IEnumerable<KeyValuePair>.
This was made because this collection of items shouldn’t be modified.
As i can see these are the same but IEnumerable dosn’t implement the Add, remove etc, this made this perfect for me and my area of using this collection.
public IDictionary<string, UserInformation> MyItems;
public IEnumerable<KeyValuePair<string, UserInformation>> MyItems;
Now to my questions.
- Is this the smartest way to go if i don’t want the collection to be
modified? - Is there a smarter way in doing this?
- Am i being stupid doing like this?
I found simular posts to this before but none actually explaining what to use and why.
The most important problem is that an
IDictionaryis designed to be used for efficient lookup. If you really only want to represent a sequence of pairs, then your approach is okay – but I wouldn’t useKeyValuePairunless the relationship is really a key/value semantically… in which case I really would just use a dictionary.You don’t have to expose the dictionary, of course – you can expose methods which only fetch the value for a key (and perhaps also expose a sequence of keys, and a sequence of values).
Or you could create a read-only implementation of
IDictionary<,>of course – there’s a sample implementation in this answer.