C# Language Collection Initializers Collection initializers

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Initialize a collection type with values:

var stringList = new List<string>
{
    "foo",
    "bar",
};

Collection initializers are syntactic sugar for Add() calls. Above code is equivalent to:

var temp = new List<string>();
temp.Add("foo");
temp.Add("bar");
var stringList = temp;

Note that the intialization is done atomically using a temporary variable, to avoid race conditions.

For types that offer multiple parameters in their Add() method, enclose the comma-separated arguments in curly braces:

var numberDictionary = new Dictionary<int, string>
{
    { 1, "One" },
    { 2, "Two" },
};

This is equivalent to:

var temp = new Dictionary<int, string>();
temp.Add(1, "One");
temp.Add(2, "Two");
var numberDictionarynumberDictionary = temp;


Got any C# Language Question?