Why is this c# snippet legal?

余生长醉 提交于 2019-12-10 02:41:55

问题


Silly question, but why does the following line compile?

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

As you can see, I haven't entered in the second element and left a comma there. Still compiles even though you would expect it not to.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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(),

};



回答6:


Same goes for enums:

enum Foo
{
  Bar,
  Baz,
};


来源:https://stackoverflow.com/questions/2361265/why-is-this-c-sharp-snippet-legal

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