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: ,,

5 Comments

  • 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!

  • Enums have the same feature:

    public enum MyEnum

    {

     Option1,

     Option2,

     Option3,

    }

    Nice thinking of the language designers.

  • 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.

  • This is also the case for Enums as well.

  • 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.

Comments have been disabled for this content.