New Foo {A = 1,} Error or function?

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 initializer of the object.

Is this legal C # and does it have any useful purpose, or did I just hit a (benign) compiler error?

+5
source share
3 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 this feature for convenience - it is especially useful if the code is generated programmatically, if you do not have a special case for the first or last element. You will find a similar syntax in enumeration declarations, assigning a property in the initialization of an object, arrays, list, etc.

, , . , , , .

,

enum Cars
{
   Honda,
   Hyundai,
   //Ford
}

. Jon Skeet .NET , python

Food for thought: If it had no use why would it be there in the first place?

+9

, :

var f = new Foo {
    A = 1,
//  B = 4
};

[Flags]
enum Characteristics
{
    None = 0,
    Big = 1,
//  Strong = 2
}

var primes = new int[] {
    2,
    3,
//  5
};
+4

.

0

All Articles