3

In looking through some legacy code, I came across this enum:

    public enum cmdResults 
    {
        cmdNotFound = 0,    
        cmdFound    = 1,    
        cmdExit     = 2,    
        cmdSuccess  = 3,    
        cmdFail     = 4,    
        cmdTimeout  = 5,    
        cmdProcess  = 6,
        cmdAddTime  = 7,
    };

On noting the comma following the final enum member, I was stunned; I removed it, and, as expected, it still compiled. But why does it work with that final comma?

(And that's not mentioning the strange-to-me ordering of members; I would either put a new "cmdNothing" at index 0, or at least have "cmdFail" take that spot)

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • The ordering could be explained by the enum values growing over time. New values can't replace existing ones otherwise any code calling this - the enum is public after all - would break. – ChrisF Mar 19 '13 at 20:55

2 Answers2

11

Because the C# compiler writers choose to make an optional comma at the end a valid syntax.

I very much like this, as it means you don't need to special case the last line. You can copy-paste lines around, add new lines at any position (including the end) without thinking about where it is, remove lines without needing to fix commas, etc. There is no ambiguity or other problems introduced by allowing the superfluous comma.

Servy
  • 202,030
  • 26
  • 332
  • 449
3

It compiles because it's legal syntax.