C# has a feature that lets you always have a comma after an item in initializers even if they are the last property or item. For example this is all valid code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var value = new | |
{ | |
Foo = "Bar", | |
}; | |
var list = new [] | |
{ | |
"Foo", | |
"Bar", | |
}; |
I am of the opinion that you should always include the comma even when it is the last item as it makes source diffs cleaner later if you need to add or remove an item. For example compare this diff where a comma wasn’t included for the last property, with the next one where a comma was used for the last item.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var anon = new | |
{ | |
- Foo = "Bar" | |
+ Foo = "Bar", | |
+ Greeting = SomeMethod() | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var array = new [] | |
{ | |
"Hello", | |
+ "World", | |
}; |
I think you will agree it is much easier to identify what changed in the second example. The same holds true for when you remove a property or item from you initializer. The source diff will always be clean if you always use a comma, so use it!