LJM
LJM

Reputation: 6454

C# Hashtable Add vs Indexer - Why have both?

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.

Upvotes: 1

Views: 1366

Answers (2)

Ioan Alexandru Cucu
Ioan Alexandru Cucu

Reputation: 12279

It might be part of the application's logic that the object you're adding should not already be there. In case the object is already there, a programming error was probably committed in the code elsewhere. Cases like these are usually flagged with exceptions or assertions. Having a method which raises the exception for you avoids you having to write code like:

if 'key' in my_dict:
    raise ProgrammingErrorElsewhere()
my_dict['key'] = obj

Upvotes: 1

JeffSahol
JeffSahol

Reputation: 971

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?

Upvotes: 3

Related Questions