.NET Enumeration allows comma in the last field

Viewed 5907

Why is this .NET enumeration allowed to have a comma in the last field?
Does this have any special meaning?

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

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 355/Section 17.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.

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, };

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

Why add trailing commas

Why you should take advantage of this feature when writing code manually?

  1. The resultant patches have less lines affected. This makes them easier to read and review.
  2. Automatic merge and conflict resolution are more accurate because there isn't extra noise to confuse the algorithm.

Examples

Without trailing comma (okay)

Example of adding a line when the previous developer didn't leave a trailing comma:

@@ -119,7 +119,8 @@ namespace SomeApp.Example
   {
     NameTitle = contact.NameTitle,
     GivenName = contact.GivenName,
-    FamilyName = contact.FamilyName
+    FamilyName = contact.FamilyName,
+    ProperName = contact.ProperName
   },
   ContactTelephone1 = contact.ContactTelephone1,
   ContactType = contact.ContactType,

Without trailing comma (better)


Example of adding a line when the previous developer left a trailing comma:

@@ -122,2 +122,3 @@ namespace SomeApp.Example
     FamilyName = contact.FamilyName,
+    ProperName = contact.ProperName,
   },

Note there is one line added in the latter vs one removed and two added. This is much easier for human and machine alike to deal with.

Why did they add it to C#?

As for why it is allowed, as per other answers:

The C# Specification (Page 355/Section 17.7) states:

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.


This applies to array initializers, object initializers and enums.

Related