In .Net, IDictionary<K, V>
defines .Keys
and .Values
properties, each of which is an ICollection<>
rather than IEnumerable<>
, which seems like it would be a more natural fit to me.
Is there any reasonable use case to call .Add
or .Remove
on .Keys
or .Values
of an instance of an IDictionary<K, V>
?
No, probably no reasonable use case. There are very few (probably zero) legitimate reasons for this at all.
The
Dictionary<TKey, TValue>
class returns aKeyCollection
for its.Keys
which in turn throwsNotSupportedException
with "Mutating a key collection derived from a dictionary is not allowed." whenever trying to add directly to it. I imagine that it returns anICollection
for legacy reasons and probably should be avoided at all costs now.In fact unless the
ICollection
returned from.Keys
had a reference to its containingIDictionary
, I can't see anything useful happen. The.Add
of theICollection
would have to tell the containingIDictionary
what this add meant. Perhaps you wanted to implement some form of aSet
you could do something like this:Surely there is a better way to implement this or similar for your specific needs. The only benefit this has is allowing
.Add
on the returnedKeys
StringCollection
. I would want to force people using myStringSet
to use the parentStringSet
class anyway. But, it is possible that someone would want the above overridden behavior.Call it with this:
I can't think of any reasonable use case for calling
Add
orRemove
on the key or value collections. What would you expect the resulting dictionary to look like?I'm pretty sure that all of the framework's built-in implementations of
IDictionary<K,V>
will throw aNotSupportedException
, or similar, if you try to do it. (And you should probably do the same thing in any of your own implementations too.)