tags:

views:

265

answers:

4

Why in this planet .NET enumeration are allowed to have comma in the last field? Is this has any special meaning?

[FlagsAttribute]
public enum DependencyPropertyOptions : byte
{
           Default = 1,
           ReadOnly = 2,
           Optional = 4,
           DelegateProperty = 32,
           Metadata = 8,
           NonSerialized = 16,
}
+15  A: 

It has no special meaning, just the way the compiler works, it's mainly for this reason:

[FlagsAttribute]
public enum DependencyPropertyOptions : byte
{
           Default = 1,
           ReadOnly = 2,
           Optional = 4,
           DelegateProperty = 32,
           Metadata = 8,
           NonSerialized = 16,
           //EnumPropertyIWantToCommentOutEasily = 32
}

By comment request: This info comes straight out of the C# Specification (Page 363/Section 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."

Nick Craver
The compiler works in accordance to the language specification (with, I think, a few exceptions). The language grammar specifies that the extraneous comma is legal in this case (and in a few others such as object initializers, collection initializers and array initializers). Also, unless you know for a fact that the grammar was designed for that reason, it's probably more correct to say that it gives the benefit you list. I wouldn't claim to know the motives of the language committee without first-hand knowledge of such.
Jason
@jason - it makes sense though
Vadi
@Jason To clarify, this isn't my thought, it's actually noted in the C# specification: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf (Page 363/Section 19.7) "Like Standard C++, C# allows a trailing comma at the end of an array-initializer. This syntaxprovides flexibility in adding or deleting members from such a list, and simplifies machine generation ofsuch lists."
Nick Craver
@Nick Craver: Very nice! I did not recall that passage. It would be great if you lifted that into your answer. Plus one from me.
Jason
+4  A: 

For the same reason this is perfectly legal:

while ( someCondition )
{
     DoSomething();;;;;;;;;;;;;;;;;;
}

The comma, or semicolon in this case, is a statement separator, and a null statement is a legal statement.

Bob Kaufman
1. The terminals of the grammar for an `enum-declaration` are identifiers or identifier = constant expression, not statements. 2. The comma is not a statement separator in C#.
Jason
+5  A: 

Also (to Nick Craver post) its much easier to add new enumerations.

This behaviour appropriate not uniquely to enums. Consider following:

var list = new int[] { 1, 2, 3, };
Sergey Teplyakov
+1  A: 

One other reason: It makes it easier to code gen.

Chris Lively