Collection Initializers - CSharp Collection

CSharp examples for Collection:Basics

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 compiler translates this to the following:

using System.Collections.Generic;
...

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

This requires that the enumerable object implements the System.Collections.IEnumerable interface and that it has an Add method that has the appropriate number of parameters for the call.

You can similarly initialize dictionaries as follows:

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

Or, as of C# 6:

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

The latter is valid not only with dictionaries, but with any type for which an indexer exists.


Related Tutorials