CSharp - Collection Collection Initializers

Introduction

You can instantiate and populate an enumerable object in a single step.

For example:

using System.Collections.Generic;
...
List<int> list = new List<int> {1, 2, 3};

The code above is the same as the following:

using System.Collections.Generic;
...

List<int> list = new List<int>();
list.Add (1);
list.Add (2);
list.Add (3);

You can initialize dictionaries as follows:


var dict = new Dictionary<int, string>()
{
       { 5, "five" },
       { 10, "ten" }
};

Or more succinctly:

var dict = new Dictionary<int, string>()
{
    [3] = "three",
    [10] = "ten"
};

The code above is valid with any type with an indexer exists.

The collection class has to implement proper Add method and support enumerable interface