Can I make sure that in dictionary in C# there will be only a single of a specific value in it?
Not as such (it wouldn't follow the the normal dictionary contract at that point), but it sounds like you effectively want a bi-directional dictionary. You can do that by composing two dictionaries, one going in each direction. I have an answer on another question with sample code for that.
That will allow you to go directly from "value" to "key" - if you have no need for that, you could always just keep a HashSet<TValue>
as well as the normal TDictionary<TKey, TValue>
and throw an exception if the caller tries to add a value which already exists.
Again, I would urge you not to do this by deriving from Dictionary<,>
- instead just compose a Dictionary<,>
and a HashSet<>
. (I wouldn't even implement IDictionary<,>
, as you have additional constraints which normal dictionaries don't include.)