FirstStep FirstStep - 10 months ago 50
C# Question

What is the difference between Dictionary.Item and Dictionary.Add?

Reading the accepted answer of C# Java HashMap equivalent, it literary states:

C#'s Dictionary uses the Item property for setting/getting items:

  • myDictionary.Item[key] = value

  • MyObject value = myDictionary.Item[key]

And when trying to implement it, I get an error when using:

myDictionary.Item[SomeKey] = SomeValue;

Error: CS1061 'Dictionary' does not contain a definition for

And I will need to use a
myDictionary.Add(SomeKey, SomeValue);
instead same as this answer and MSDN - Dictionary in order to resolve the error.

The code is fine, but out of curiosity am I doing anything wrong? Other than one does not compile, what is the difference between

Dictionary.Item[SomeKey] = SomeValue;


Dictionary.Add(SomeKey, SomeValue);


I edited the accepted answer in C# Java HashMap equivalent. See edition history to know why.

Evk Evk
Answer Source

Difference is simple

Dictionary[SomeKey] = SomeValue; // if key exists already - update, otherwise add
Dictionary.Add(SomeKey, SomeValue); // if key exists already - throw exception, otherwise add

As for the error

Error: CS1061 'Dictionary' does not contain a definition for 'Item'

C# allows for "default" indexer, but how it should be implemented internally? Remember that there are many languages working with CLR, not just C#, and they would also need a way to call that indexer.

CLR has properties, and it also allows to provide arguments when those properties getters or setters are called, because properties are really compiled as a pair of get_PropertyName() and set_PropertyName() methods. So, indexer can be represented by a property which getter and setter accept additional arguments.

Now, there cannot be property without a name, so we need to choose a name for the property which represents our indexer. By default, "Item" property is used for the indexer property, but you can overwrite it with IndexerNameAttribute.

Now when indexer is represented as regular named property, any CLR language can called it with get_Item(index).

That's why in article you linked that indexer is referenced by Item. Though when you use it from C#, you have to use appropriate syntax and just call it as

Dictionary[SomeKey] = SomeValue;