I’m aware that the hashtable’s Add and assignment-via-indexer operations are different (i.e. the latter will allow for overwriting while the former throws a “Item has already been added. Key in dictionary:…” exception). My question is what situation could arise that you’d ever want to add something, but throw an exception if it’s already there?
Specifically, it seems like this is just an encapsulation of two more atomic operations (Contains and the assignment-via-indexer) and I cannot come up with a single scenario where I’d want Microsoft to handle this in an encapsulated way.
EDIT: I fully support the idea that exceptional cases should throw exceptions, and that Add (while simply an encapsulation) provides the exception when the given key is already in the dictionary. However, typically Hashtables and Dictionaries are used for quick lookups from keys to values. In addition, most of the time when I’m building one, I already have the entire collection available and I’m simply translating it to a dictionary.
An example just hit me… I could imagine a scenario where you’re using a hashtable (or dictionary) to track the session of users logged into a particular session. And if you have a specific requirement that each user can only be logged in from one location at a time (and that they must log out of one session before logging in again), then you may want Add because it more clearly defines the intent of the code.
The scenario where the exception-throwing behavior is desirable is where you don’t expect the value to be there, ever, so that finding it there would be an exception, an indication that something went wrong. You would not want to have to do a Contains test for every added element if you never expect the key to be there already, right?