c# define dictionary code example

Example 1: c sharp create dictionary

// To initialize a dictionary, see below:
IDictionary<int, string> dict = new Dictionary<int, string>();
// Make sure to give it the right type of key and value

// To add values use 'Add()'
dict.Add(1,"One");
dict.Add(2,"Two");
dict.Add(3,"Three");

// You can also do this together with the creation
IDictionary<int, string> dict = new Dictionary<int, string>()
{
	{1,"One"},
	{2, "Two"},
	{3,"Three"}
};

Example 2: declare dictionary c#

var students2 = new Dictionary<int, StudentName>()
        {
            [111] = new StudentName { FirstName="Sachin", LastName="Karnik", ID=211 },
            [112] = new StudentName { FirstName="Dina", LastName="Salimzianova", ID=317 } ,
            [113] = new StudentName { FirstName="Andy", LastName="Ruth", ID=198 }
        };

Example 3: c# dictionaries

IDictionary<int, string> dict = new Dictionary<int, string>();
        
//or

Dictionary<int, string> dict = new Dictionary<int, string>();

Example 4: dictionary c#

var cities = new Dictionary<string, string>(){
	{"UK", "London, Manchester, Birmingham"},
	{"USA", "Chicago, New York, Washington"},
	{"India", "Mumbai, New Delhi, Pune"}
};

Example 5: c sharp add item to dictionary

// To add an item to a dictionary use 'Add()'
dict.Add(1,"One");