-->

C# 6.0 New Features - Index Initializers

dev csharp

In current C# a collection initialization can be done like this:

var result = new Dictionary<string, string>();
result.Add("index1", "value1");
result.Add("index2", "value2");

or key - value pairs can be added during initialization

var result = new Dictionary<string, string>() 
{
	{"index1", "value1"},
	{"index2", "value2"}
};

With C# 6.0 values at specific indices can be initialized like this:

var result = new Dictionary<string, string>() 
{
	["index1"] = "value1",
	["index2"] = "value2"
};

It’s a shorthand but not so much! I don’t see much value in this notation but I’m sure in time it will prove itself. I don’t think the guys in the language team are just adding random features!