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.
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.
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
.
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(),
};
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.
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.