开发者

Is IDictionary[index] is misused?

During my C# coding e开发者_高级运维xperience 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.


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...)


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜