John Liu .NET

View Original

Quick tip: Initialising Dictionary inline

var dictionary = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" },
};


var list = new List<string>
{
"value1",
"value2",
"value3",
};

You might notice that I like to leave the comma behind the last element in my inline initializers - this is actually unnecessary.  But having it there means that I can copy/paste entire lines and move them around without worrying about missing comma right at the end.


For example, this is valid code:

var list = new List<string>
{
"value1",
"value2",
"value3"
};
But if I had to swap the order of the elements and end up with this code, this is not valid.
var list = new List<string>
{
"value1",
"value3"
"value2",
};