What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , trackbacks - 0

My Links

News

Archives

Post Categories

Check These Out

Gurus

QuickTip: Did You Know??? Auto-Adding Dictionary entries

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.

Print | posted on Monday, October 19, 2009 4:21 AM | Filed Under [ Visual Studio ]

Feedback

Gravatar

# re: QuickTip: Did You Know??? Auto-Adding Dictionary entries

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.
10/19/2009 5:33 AM | Bill
Gravatar

# re: QuickTip: Did You Know??? Auto-Adding Dictionary entries

OOps, my mistake - the remarks section has the information about the Setter adding items instead of throwing KeyNotFoundException.
10/19/2009 6:14 AM | Bill
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: