This isn't an error?

I just saw something odd in a diff before a check-in.  Basically, I had a trailing comma in an object initializer:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var foo = new Foo
                      {
                          A = "A",
                        B = "B",
                      };
        }
    }
 
    class Foo
    {
        public string A { get; set; }
        public string B { get; set; }
    }
}

I thought this would be an error until I did some searching and found that it is allowed according to "ECMA-334: 19.7 Array initializers":

[Note: Like Standard C++, C# allows a trailing comma at the end of an array-initializer. This syntax provides flexibility in adding or deleting members from such a list, and simplifies machine generation of such lists. end note]

Technorati Tags: ,,
Published Wednesday, October 07, 2009 11:27 AM by PSteele
Filed under:

Comments

# Twitter Trackbacks for This isn't an error? - Patrick Steele's .NET Blog [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 This isn't an error? - Patrick Steele's .NET Blog         [asp.net]        on Topsy.com

# re: This isn't an error?

We had some guys in from Rock Solid who did this exact thing and I was sure it was a bug. They argued it helped readability and as you mentioned simplified machine generation.

I still looks wrong to me though!

Thursday, October 08, 2009 4:52 AM by Ross

# re: This isn't an error?

Enums have the same feature:

public enum MyEnum

{

 Option1,

 Option2,

 Option3,

}

Nice thinking of the language designers.

Thursday, October 08, 2009 5:10 AM by Tommy Carlier

# re: This isn't an error?

The trailing comma is allowed for the last element in an enum. I like this a lot as it helps me to move the elements around without forgetting the comma or simply adding another one at the end of the list.

Thursday, October 08, 2009 8:28 AM by Brian Di Croce

# re: This isn't an error?

This is also the case for Enums as well.

Thursday, October 08, 2009 9:06 AM by DanO

# re: This isn't an error?

I almost always leave a trailing comma for enums, arrays, object initializers, and collection initializers.

And on a website roll-out, I almost always get hit by bugs on IE6, which doesn't allow them in object initializers in javascript.

Tuesday, October 13, 2009 11:04 AM by Thomas G Mayfield

# ???????? ?????????????? #5 | ?? ?????????? ???? ??????????.

Pingback from  ???????? ?????????????? #5 | ?? ?????????? ???? ??????????.