Monday, September 10, 2007

 

Trailing Commas

Some people may have "accidentally" stumbled across a feature of the C# programming language:

In a list of items separated by commas, the last item in that list may have a comma even though it is not followed by another item.

For example, both of the following enum declarations are perfectly valid; the compiler will not generate a syntax error when it reaches the comma after enum value Value2C.


public enum MyEnum1
{
Value1A,
Value2A,
Value3A
}

public enum MyEnum2
{
Value2A,
Value2B,
Value2C,
}


This is indeed a feature of the C# language, and is not bug in the compiler; the comma is truely optional and is modeled after the C99 and C++ standards. Allowing the optional, trailing comma not only makes it easier for developers to rearrange and comment-out items in the list, but also makes it easier to programmatically-generate C# source code.

The optional, trailing comma can be used in three places as indicated by sections 19.7, 21.1 and 24.2 of the ECMA-334 standard:

§19.7: "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."

§21.1: "C# allows a trailing comma in an enum-body, just like it allows one in an array-initializer (§19.6)"

§24.2: "For convenience, a trailing comma is allowed in a global-attribute-section and an attribute-section, just as one is allowed in an array-initializer (§19.6)."

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]