1 min read
Initialize a dictionary with a collection initializer in C# Part 2 – Initialize a Dictionary
With our new class in place let’s write some code to initialize a dictionary with instances of the Student class.
¨First add the using statement for the generic collections and your own namespace so the class you created is available.
using System.Collections.Generic;
using CODEGROUND;
// your namespace
Now, this initialization uses the add method that the compiler generates a call to for each of the pairs key value.
var students = new Dictionary<int, Student>()
{
{ 100, new Student { ID = 100, FirstName = "Sherlock", LastName = "Holmes"} },
{ 101, new Student { ID = 101, FirstName = "John", LastName = "Watson"} }
};
Great! Now in the next and last post we’ll loop through the dictionary.