Collection classes may need to be populated directly from constant data.
In C# 2.0 you were forced to either write multiple lines of Add
statements or transform it from an array. C# 3.0 allows you to specify an initializer using curly brackets {}
to provide necessary initial data.
Code
C#
var phonetics = new List<string>()
{ "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf" };
C#
var phonetics = new List<string>();
phonetics.Add("Alpha");
phonetics.Add("Bravo");
phonetics.Add("Charlie");
phonetics.Add("Delta");
phonetics.Add("Echo");
phonetics.Add("Foxtrot");
phonetics.Add("Golf");
C#
var phonetics = new Dictionary<string, string>()
{
{ "A", "Alpha" },
{ "B", "Bravo" },
{ "C", "Charlie" },
{ "D", "Delta" },
{ "E", "Echo" }
};
C#
var phonetics = new Dictionary<string, string>();
phonetics.Add("A", "Alpha");
phonetics.Add("B", "Bravo");
phonetics.Add("C", "Charlie");
phonetics.Add("D", "Delta");
phonetics.Add("E", "Echo");
Notes
- When creating a dictionary if there is something on the value that can derive the key create an array of the values and then
ToDictionary()
with the key specification - The compiler replaces collection initializers with multiple calls to any method named
Add
on the class - Index initializers C# 6.0 added support for indexers to be used in initializers too