Dictionaries in C#

Dictionaries, like hashtable store data in the form of key-value pairs. However, unlike you need to define the type of those key and value pairs at the time of defining the dictionary. Dictionary collection belongs to System.Collections.Generic namespace. All the collections belonging to this namespace are type-safe which means that the type of the items in the dictionary are checked at run-time and if the type doesn’t match, the compiler gives error. This is unlike hashtable where you could store any object in place of key, as well as a value. Have a look at the following example to understand dictionaries.

´╗┐using System;
using System.Collections.Generic;
using System.Threading;

namespace CSharpTutorials {
    class Tutorial  {
        static void Main() {
            Dictionary<int, string> stud_dic = new Dictionary<int, string>();
            // Adding Items in a Dictinary
            stud_dic.Add(20, "Johny");
            stud_dic.Add(15, "Liza");
            stud_dic.Add(11, "Sherry");
            stud_dic.Add(1, "Tommy");
            stud_dic.Add(21, "Johny");
            stud_dic.Add(12, "Ali");

            // Retrieving item using key
            Console.WriteLine("The student with roll number 11 is "+stud_dic[11]);

            // Checking if a dictionary contains key or value
            Console.WriteLine("If the key 20 exists in dictionary:" + stud_dic.ContainsKey(20));
            Console.WriteLine("If the value Johny exists in dictionary:" + stud_dic.ContainsValue("Johny"));

            // Clearing a Dictionary

Download the code

In the above code a Dictionary object named stud_dic has been created. Notice the declaration of the Dictionary object, here key and value type has been specified, separated by comma within less than and greater than symbol. For stud_dic object, the key can only be of integer type while the value should be of string type. This Dictionary will not accept any other type as Key and value other than integer and string type respectively.

In stud_dic object, the key can be considered as the roll number while the value is the name of the student. You can access student name via his key as in the above example. Also, a key is always unique. For instance you cannot store 10 as key for two items in the stud_dic Dictionary object.

<<< Multi-threaded Programming in C#File Reading and Writing in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .