C# Generic Dictionary<Tkey, Tvalue> Tutorial with Example

In this chapter you will learn
  1. What are Generic Dictionary Class?
  2. How to declare it?
  3. Programming Example

What are Generics Dictionary Class?

Dictionary is a collection of keys and Values. We bind values with keys and store them in the dictionary and later that key is used for accessing dictionary value. Generic Dictionary is type safe and avoid boxing and unboxing and provides the complete benefit of Dictionary.Generic Dictionary belongs to System.Collection.Generic namespace.

Generic Collection doesn't allow inserting duplicate keys.
Important Methods of Generic Dictionary Class

Properties

Properties Usage
Comparer Gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary.
Count Gets the number of key/value pairs contained in the Dictionary<TKey, TValue>.
Item[TKey] Gets or sets the value associated with the specified key.
Keys Gets a collection containing the keys in the Dictionary<TKey, TValue>.
Values Gets a collection containing the values in the Dictionary<TKey, TValue>.

Methods

Methods Usage
Add(TKey, TValue) Adds the specified key and value to the dictionary.
Clear() Removes all keys and values from the Dictionary<TKey, TValue>.
ContainsKey(TKey) Determines whether the Dictionary<TKey, TValue> contains the specified key.
ContainsValue(TValue) Determines whether the Dictionary<TKey, TValue> contains a specific value.
Equals(Object) Determines whether the specified object is equal to the current object.(Inherited from Object.)
Finalize() Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)
GetEnumerator() Returns an enumerator that iterates through the Dictionary<TKey, TValue>.
GetHashCode() Serves as the default hash function. (Inherited from Object.)
GetObjectData (SerializationInfo, StreamingContext) Implements the System.Runtime .Serialization.ISerializable interface and returns the data needed to serialize the Dictionary<TKey, TValue> instance.
GetType() Gets the Type of the current instance.(Inherited from Object.)
MemberwiseClone() Creates a shallow copy of the current Object.(Inherited from Object.)
OnDeserialization(Object) Implements the System.Runtime .Serialization.ISerializable interface and raises the deserialization event when the deserialization is complete.
Remove(TKey) Removes the value with the specified key from the Dictionary<TKey, TValue>.
ToString() Returns a string that represents the current object.(Inherited from Object.)
TryGetValue(TKey, TValue) Gets the value associated with the specified key.

Programming Example

using System;
using System.Collections.Generic;

namespace GenericDictionary
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Declare Generic Collection
            Dictionary<string,string> movie=new Dictionary<string,string>();

            //Adding Item in Collection
            movie.Add("sci-fi","Star Wars");          
            movie.Add("Action","The One");
            movie.Add("Fantacy","Star Dust");
            movie.Add("Computer","Algorithm");
            movie.Add("Love","50 First Dates");
            
            //Printing single item
            Console.WriteLine(movie["sci-fi"]);

            //Iterate Dictionary
            foreach(KeyValuePair<string,string> items in movie)
            {
                Console.WriteLine(items.ToString());
            }

            //Find items
            if(movie.ContainsKey("sci-fi"))
            {
                Console.WriteLine("Key found. Value is "+movie["sci-fi"]);
            }
            else
            {
                Console.WriteLine("Key Not Found");
            }
        }
    }
}

Output

Star Wars
[sci-fi, Star Wars]
[Action, The One]
[Fantacy, Star Dust]
[Computer, Algorithm]
[Love, 50 First Dates]
Key found. Value is Star Wars
_

Summary

In this chapter you learned Generic Dictionary<Tkey, Tvalue> class with complete programming example. In the next chapter you will learn Generic SortedList<Tkey,Tvalue>.

More Articles