SiberianGuy
SiberianGuy

Reputation: 25312

Is IDictionary[index] is misused?

During my C# coding experience I saw a lot of pieces of code where IDictionary[index] setter was used to add new values:

var dictionary = new Dictonary<long, string>();
...
dictionary[1] = "one"; //assume we want to add new value here

So instead of using dictionary.Add(1, "one") developer rewrites the old value (if it existed) by indexer call (which is equal to AddOrUpdate operation);

I think dictionary should throw an exception when you try to set a value to already existing key (like it throws when you try to get non existing key). It's an argumentative statement but I would like to compare my opinion to your's.

Upvotes: 1

Views: 445

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502316

What would be the point of having two members which did exactly the same thing?

If you want to effectively use the dictionary as an associative array, assigning in the same way as you would for an array, use the indexer. If you want a more "guarded" addition to the dictionary, use Add.

Making the indexer throw on an existing entry would make it behave totally differently to indexers for other collections such as arrays and lists.

(EDIT: Note that the dictionary indexer already acts slightly differently of course, by throwing an exception when you try to fetch an entry which hasn't been given a value. In some ways that's the same as accessing an index which is out of range, I suppose...)

Upvotes: 6

Antony Blazer
Antony Blazer

Reputation: 705

Why it should be? As for me it is normal behavior. How do you want to update value in dictionary? As far as i have understood you, developer should remove this keyvaluepair and than only add new keyvaluepair in dictionary, isn't it?

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351566

It's definitely a matter of opinion and I personally prefer the existing behavior. Nothing is stopping you from creating a custom type that implements IDictionary<TKey,TValue> and provides the behavior you are looking for.

Upvotes: 0

Related Questions