What Was I Thinking?

Follies & Foils of .NET Development

  Home  |   Contact  |   Syndication    |   Login
  41 Posts | 0 Stories | 97 Comments | 0 Trackbacks

News

Archives

Post Categories

Check These Out

Gurus

When adding an item to a dictionary, I always thought you had to use the Add() method, like this:

string key = "MyKey";
int value = 20;
var myDictionary = new Dictionary<string, int>();
myDictionary.Add(key, value);

Apparently, you can directly reference it in the collection, and if the key doesn’t exist, its auto-added to the collection

string key = "MyKey";
int value = 20;
var myDictionary = new Dictionary<string, int>();
myDictionary[key] = value;

most likely you already knew this.  I did not.  Its the little things I guess.

posted on Monday, October 19, 2009 4:21 AM

Feedback

# re: QuickTip: Did You Know??? Auto-Adding Dictionary entries 10/19/2009 5:33 AM Bill
Most likely not (in my case), since the documentation specifically states that an exception (KeyNotFoundException) would be thrown in the case shown above. (The Item property is the default property).

http://msdn.microsoft.com/en-us/library/9tee9ht2.aspx

It does not, as you have found.

# re: QuickTip: Did You Know??? Auto-Adding Dictionary entries 10/19/2009 6:14 AM Bill
OOps, my mistake - the remarks section has the information about the Setter adding items instead of throwing KeyNotFoundException.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: