C# Dictionary Edit

Rakesh Kumar Sutar | 20 January 2021 | 159

Introduction

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the dictionary is grows according to the need.

Characteristics

  • The Dictionary class implements the
  • IDictionary<TKey,TValue> Interface
  • IReadOnlyCollection<KeyValuePair<TKey,TValue>> Interface
  • IReadOnlyDictionary<TKey,TValue> Interface
  • IDictionary Interface
  • In Dictionary, the key cannot be null, but value can be.
  • In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception.
  • In Dictionary, you can only store same types of elements.
  • The capacity of a Dictionary is the number of elements that Dictionary can hold.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hello_World
{
    class Program
    {
        static void Main(String[] args)
        {
           
            Dictionary My_dict1 =
                           new Dictionary();

            
            My_dict1.Add(1, "Welcome");
            My_dict1.Add(2, "MR");
            My_dict1.Add(3, "Rakesh Kumar Sutar");

            foreach (KeyValuePair ele1 in My_dict1)
            {
                Console.WriteLine("\t"   "{0}  {1}",
                          ele1.Key, ele1.Value);
            }
            Console.WriteLine();

           
            Dictionary My_dict2 =
                    new Dictionary(){
                                  {"1st", "MUMBAI"},
                                  {"2nd", "BANGLORE"},
                                {"3rd", "DELHI"} };

            foreach (KeyValuePair ele2 in My_dict2)
            {
                Console.WriteLine("\t" "{0}  {1}", ele2.Key, ele2.Value);
            }
            Console.ReadLine();
        }
    }
}

Output