tags:

views:

124

answers:

5

This one has always puzzled me, but i'm guessing there is a very sensible explanation of why it happens.

When you have a collection initializer the compiler allows a trailing comma, e.g.

new Dictionary<string, string>
{
    { "Foo", "Bar "},
};

and

new List<string>
{
    "Foo",
};

Anyone know why this trailing comma is allowed by the compiler?

+2  A: 

It's a programmer convenience since the developer can simply copy and paste the last line to extend the list. C#/.NET is good like this :)

mythz
+3  A: 

Probably mainly for tools like code generators, where is it hugely convenient not to have to know if this is the first or last item. Arguably this shouldn't be a determining factor, but (having written such tools) I am grateful for it.

Marc Gravell
+2  A: 

I am guessing for two reasons:

  1. It would have been extra work to have the compiler recognise and treat the last line differently to the others.
  2. It is actually handy to have the trailing comma as it allow lines to be arranged without causing unnecessary build failures.
Paul Ruane
A: 

When you change this:


     new List<string>
     { 
         "Foo", 
     }; 

to that:


     new List<string>
     { 
         "Foo", 
         "Bar", 
     }; 

Diff-Tools will only highlight the added line. So e.g. during code review, you only have to check the new line.

Henrik