Why is this c# snippet legal?

这一生的挚爱 提交于 2019-12-05 02:07:59

I suppose because the ECMA 334 standard say:

array-initializer:
    { variable-initializer-list(opt) }
    { variable-initializer-list , }
variable-initializer-list:
    variable-initializer
    variable-initializer-list , variable-initializer
variable-initializer:
    expression
    array-initializer

As you can see, the trailing comma is allowed:

{ variable-initializer-list , }
                            ↑

P.S. for a good answer (even if this fact was already pointed by many users). :)

Trailing comma could be used to ease the implementation of automatic code generators (generators can avoid to test for last element in initializer, since it should be written without the trailing comma) and conditional array initialization with preprocessor directives.

This is syntax sugar. In particular, such record can be useful in code generation.

int[] i = new int[] {
    1,
    2,
    3,
};

Also, when you are writing like this, to add new line you need to add text only in single line.

It should compile by definition.

There is no second element. A trailing comma is valid syntax when defining a collection of items.

i is an array of int containing a single element, i[0] containing the value 1.

Another benefit of allowing a trailing comma is in combination with preprocessor directives:

int[] i = new[] {
#if INCLUDE1
   1,
#endif

#if INCLUDE2
   2,
#endif

#if INCLUDE3
   3,
#endif
};

Without allowing a trailing comma, that would be much more difficult to write.

its so you can do this and copy/paste lines around without worrying about deleting/adding the commas in the correct places.

int[] i = new[] { 
   someValue(),
   someOtherValue(),
   someOtherOtherValue(),

   // copy-pasted zomg! the commas don't hurt!
   someValue(),
   someOtherValue(),
   someOtherOtherValue(),

};

Same goes for enums:

enum Foo
{
  Bar,
  Baz,
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!