Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Foo { A = 1, } Bug or Feature?

Tags:

c#

c#-4.0

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?

like image 439
Branko Dimitrijevic Avatar asked May 24 '12 12:05

Branko Dimitrijevic


1 Answers

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?

like image 140
Nikhil Agrawal Avatar answered Nov 14 '22 23:11

Nikhil Agrawal