4

Was surprised to see that a C# Enum definition seems to allow an extra comma at the end (at least in VS2010).

e.g. :

public enum EnumTest1
{
    Abc,
    Def,
}

i.e. there is a comma at the end of "Def". Just wondering if this is allowed by design, or is an oversight. (This might be good to know, because if it is a bug, there may be no guarantees that code like the above will compile in future versions of C#).

Moe Sisko
  • 11,665
  • 8
  • 50
  • 80
  • sorry, this is duplicate of : http://stackoverflow.com/questions/792753/is-the-last-comma-in-c-enum-required?rq=1 (maybe not ?, that post was for C, not C#.) – Moe Sisko Oct 11 '12 at 23:32
  • There is nothing wrong with that, same behavior exists in syntax like new obj {a = 1, b = 2,} – AD.Net Oct 11 '12 at 23:32
  • This will still compile in Visual Studio 2012, currently tested :D – John Woo Oct 11 '12 at 23:32
  • actually, this is a dup of : http://stackoverflow.com/questions/2147333/net-enumeration-allows-comma-in-the-last-field and http://stackoverflow.com/questions/5126483/unnecessary-comma-in-enum-declaration?rq=1 . Sorry I didn't search more thoroughly. – Moe Sisko Oct 12 '12 at 00:16
  • I'm surprised that it is allowed to exclude it, at least there should be an option to enforce it. (as to why there are several explanations on that topic) – NiKiZe Nov 09 '19 at 12:58
  • Does this answer your question? [.NET Enumeration allows comma in the last field](https://stackoverflow.com/questions/2147333/net-enumeration-allows-comma-in-the-last-field) – DavidRR Apr 13 '20 at 11:54

1 Answers1

11

It is allowed by design. Similarly, you can have trailing commas in initializers as well. For example:

var ints = new[] { 2, 3, 4, 3, };

var obj = new SomeClass { Prop1 = "foo", Prop2 = "bar", };

I think that allowing trailing commas makes creating auto-generated code much easier because you don't have to add last-in-the-list logic when outputting a list in your code.

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • 4
    It's a syntax 'borrowed' from C/C++ and it's very handy for insert/removing lines from the enum like the one you have above. For instance if you just commented out Def the list would still be valid without you having to juggle the commas. If you wanted to add a new enum you could just add it, whereas without the trailing comma support you'd have to edit the line above as well or it wouldn't compile. – cirrus Oct 11 '12 at 23:41