Hi all,

I was wondering why the following code compiles, with or without extra komma?
My feeling is it should not be there, but apparently it does not matter. Any comments would be more then welcome.

namespace ConsoleApplication1
{
    class Program
    {
        public enum months
        {
            jan = 1,
            feb = 2,
            mar = 3,
            apr = 4, // notice the extra comma
        }

        static void Main(string[] args)
        {
            int[] strangeInts = new int[3] { 1, 2, 3, }; // notice the extra comma
            int total = strangeInts[0] + strangeInts[1] + strangeInts[2];
            Console.WriteLine("The total is: {0}", total);
            months strangeMonths = months.feb;
            Console.WriteLine("The month is: {0}", strangeMonths);
            Console.ReadKey();
        }
    }
}
kvprajapati commented: komma++ +11

Recommended Answers

All 3 Replies

I think microsoft started doing that to make life easier. I have noticed this behavior in a number of their products:

IF OBJECT_ID('#Temp', 'U') IS NOT NULL DROP TABLE #Temp
Create Table #Temp
(
  Col1 varchar(30),
  Col2 varchar(30),
  Col3 varchar(30),
)

In SQL2000 the SQL server would throw an error for that last comma in "Col3" but starting in SQL2005 it was OK. I guess they changed company policy on how that should work :)

commented: komma++ +11

Yes Scott, that must be it.
I found this "extra comma" in an enum in some old testcode I had (copy,paste thing probably) so I wondered how this old code ever did compile and worked:-O Did try it with an int array and it was the same. And from your post with the SQL example it seems to be all over the place.
Thanks for the reply.
BTW I'm alive and kicking:)

Just FYI:

I believe this practice was carried over as the C# language was developed. In C/CPP, I got into the habit of putting in the comma after the last definition for a few reasons:

1) easier editing when you want to append to list of enums
2) easier editing when you want to reorder with cut and paste
3) easier editing when you want to search and replace, such as wanting to append characters to the end of selected items you would just replace the "," with "_FLD," or "_SIZ", etc.

In addition, we would often place a final definition to indicate the total definitions (eg. TOTFIELDS). This last entry was very useful for loops and allocations. Not so much now as C# makes life so much easier, but I still do this. However, in this particular case, you would definitely want to leave off the trailing comma because you would never want to append a definition past the TOTFIELDS.

commented: Thanks for the extra clarification! +8
commented: interesting +8
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.