c# - What is the difference between Dictionary.Item and Dictionary.Add? -


reading accepted answer of c# java hashmap equivalent, literary states:

c#'s dictionary uses item property setting/getting items:

  • mydictionary.item[key] = value
  • myobject value = mydictionary.item[key]

and when trying implement it, error when using:

mydictionary.item[somekey] = somevalue;

error: cs1061 'dictionary' not contain definition 'item'

and need use mydictionary.add(somekey, somevalue); instead same this answer , msdn - dictionary in order resolve error.

the code fine, out of curiosity doing wrong? other 1 not compile, difference between

dictionary.item[somekey] = somevalue;  

and

dictionary.add(somekey, somevalue); 

edit:

i edited accepted answer in c# java hashmap equivalent. see edition history know why.

difference simple

dictionary[somekey] = somevalue; // if key exists - update, otherwise add dictionary.add(somekey, somevalue); // if key exists - throw exception, otherwise add 

as error

error: cs1061 'dictionary' not contain definition 'item' 

c# allows "default" indexer, how should implemented internally? remember there many languages working clr, not c#, , need way call indexer.

clr has properties, , allows provide arguments when properties getters or setters called, because properties compiled pair of get_propertyname() , set_propertyname() methods. so, indexer can represented property getter , setter accept additional arguments.

now, there cannot property without name, need choose name property represents our indexer. default, "item" property used indexer property, can overwrite indexernameattribute.

now when indexer represented regular named property, clr language can called get_item(index).

that's why in article linked indexer referenced item. though when use c#, have use appropriate syntax , call as

dictionary[somekey] = somevalue; 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -