The following C# snippet compiles and runs under my Visual Studio 2010:
struct Foo {
public int A;
}
// ..
var foo = new Foo { A = 1, };
Note the trailing comma in the object initializer.
Is this legal C# and does it have any useful purpose, or I have just hit a (benign) compiler bug?
Yes it is very much legal and useful in C# to have trailing commas and no it is not a (benign) compiler bug.
Microsoft added that feature for convenience - it's especially useful if code is being generated programmatically if you don't have to special case the first or last item. You'll find similar syntax in enum declarations, assigning property in object initialization, arrays, List etc.
It allows that trailing comma simply to make it easier a more uniform to have a list of items that go in your initializer that changes length over time. For example, since you have that comma there, adding a new item to the end only involves editing one line, and not editing one line to add a comma and another line to add the new content.
Moreover what if you comment out the last option
enum Cars
{
Honda,
Hyundai,
//Ford
}
See the Jon Skeet answer for .NET now support trailing comma in array like python does
Food for thought: If it had no use why would it be there in the first place?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With