How to initialize a dictionary in c#?

In C#, the Dictionary class is used to represent a collection of keys and values.

Example:


  Dictionary ages = new Dictionary();
  ages.Add("Alice", 30);
  ages.Add("Bob", 25);
  

Solution:

For better readability and initialization, you can use collection initializers:


  Dictionary ages = new Dictionary
  {
      {"Alice", 30},
      {"Bob", 25}
  };
  

Beginner's Guide to C#