Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you have a comma at the end of a collection initializer?

Tags:

syntax

c#

c#-3.0

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?

like image 278
James Hollingworth Avatar asked Sep 09 '10 09:09

James Hollingworth


2 Answers

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.

like image 111
Marc Gravell Avatar answered Oct 29 '22 03:10

Marc Gravell


Similar reason to .NET Enumeration allows comma in the last field

like image 22
Neil Bostrom Avatar answered Oct 29 '22 03:10

Neil Bostrom