简体   繁体   中英

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

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, eg

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

and

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

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

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.

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 :)

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.

When you change this:


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

to that:


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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM