Rubens Farias
Rubens Farias

Reputation: 57996

Missing last item on enums

I was looking for some enums options, and just spotted a missing comma after last option. Take, for instance, that DayOfWeek enum (press F12 to go to definition):

public enum DayOfWeek
{
    Sunday    = 0,
    Monday    = 1,
    Tuesday   = 2,
    Wednesday = 3,
    Thursday  = 4,
    Friday    = 5,
    Saturday  = 6, // note this comma
}

Are there any reason behind this behavior?

Upvotes: 3

Views: 396

Answers (3)

Joey
Joey

Reputation: 354824

The trailing comma after the last enum member is optional. This was presumably done to aid automatic code generation which can just spit out stuff without thinking about the grammar.

Whether the comma is present or not doesn't change anything.

Take a look at the grammar:

enum-declaration:
  attributesoptenum-modifiersoptenumidentifierenum-baseoptenum-body;opt

enum-base:
  : integral-type

enum-body:
  { enum-member-declarationsopt }
  { enum-member-declarations , }

enum-member-declarations:
  enum-member-declaration
  enum-member-declarations,enum-member-declaration

enum-member-declaration:
  attributesoptidentifier
  attributesoptidentifier=constant-expression

As you see, the enum-body includes the option of a single trailing comma.

Upvotes: 8

Thomas Levesque
Thomas Levesque

Reputation: 292695

The compiler just ignores the last comma. It doesn't need to be there, but it's not an error either if you put it

Upvotes: 0

Benjamin Podszun
Benjamin Podszun

Reputation: 9837

I'm pretty sure no day of week is missing.. :)

You can have an optional comma at the end of an enum definition (works without as well). I guess that's just a convenience thing: If the world changes and you have to add a day to the week: Add a new line (and optionally end it with a comma again, for the next guy defining new days).

Upvotes: 1

Related Questions