A syntax feature in enum I didn’t know

Consider this enum declaration.

enum Gender { Female, Male, Alien, }

Do you think it compiles? Note that there is a comma after the last element. I would say that it won’t compile, at least it doesn’t look OK to me.

Guess what, it compiles and that’s so good news. Why is it good news? Simple, if you happen to use code generators (hint: [CodeSmith]) you would know that the last comma is always a pain to remove when you are autogenerating an enum, for example. Even if you know the number of elements you want to include in the enum there is some code required to remove the last coma. Let’s take a look at an example from my recent template:

public enum SomeList { <% string[] enumItems = new string[]{"One", "Two", "Three"}; for (int i=0; i<enumItems.Length; i++) { %> <%= enumItems[i ] %><% if (i<enumItems.Length-1) { %>,<% } %> <% } %> }

This code produces this output:

public enum SomeList { One, Two, Three }

To remove the last comma I had to use for instead of much more handy foreach. Furthermore I had to add an entire if clause next to the element (<% if (i<enumItems.Length-1) { %>,<% } %>) which further unnecessarily clutters the code. Quite much noise for a simple loop. Now, consider revisited version that leaves comma:

public enum SomeList { <% string[] enumItems = new string[]{"One", "Two", "Three"}; foreach (string item in enumItems) { %> <%= item %>, <% } %> }

Isn’t this much more clear and compact code? The only difference is that output leaves last comma – however as I stated above, this isn’t a problem at all.

2 thoughts on “A syntax feature in enum I didn’t know

  1. Hi Renaud,

    Well, you have to create an array beforhand and store each line into a string variable which disables asp-like output formating. But yes, it is an option.

Leave a Reply