#1,129 – Generic Dictionary Basics

The generic dictionary class, System.Collections.Generic.Dictionary<TKey,TValue>, allows you to store a collection of key/value pairs, where the both the keys and the values have a particular type.

You specify types for the keys and values when you declare an instance of the dictionary, creating a constructed type.  The example below creates an instance of a dictionary that stores an integer value for each of a set of character values.

            Dictionary<char, int> charCounter = new Dictionary<char, int>();

By default, the collection contains no entries–no key/value pairs.  You add an entry using the Add method, specifying a new key to be added, along with its value.  Note that the key is of type char and the value is of type int.

            charCounter.Add('x', 12);

If a dictionary already contains a particular key, you can retrieve the value using square bracket syntax.

            int numXs = charCounter['x'];

 

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,129 – Generic Dictionary Basics

  1. Pingback: Dew Drop – July 2, 2014 (#1806) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: