How to create a Dictionary using C#?


Dictionary is a collection of keys and values in C#. Dictionary<TKey, TValue> is included in the System.Collection.Generics namespace.

To create a dictionary, you first need to set it and add the key and values. Here we have added 5 keys with values to a Dictionary. We have set its keys and value type as int.

IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1,44);
d.Add(2,34);
d.Add(3,66);
d.Add(4,47);
d.Add(5,76);

The following is the complete code −

Example

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      IDictionary<int, int> d = new Dictionary<int, int>();
      d.Add(1,44);
      d.Add(2,34);
      d.Add(3,66);
      d.Add(4,47);
      d.Add(5,76);

      Console.WriteLine(d.Count);
   }
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 21-Jun-2020

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements