Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this c# snippet legal?

Tags:

c#

grammar

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.

like image 978
Razor Avatar asked Mar 02 '10 06:03

Razor


People also ask

What does C mean on a hard drive?

On computers running Windows or MS-DOS, the hard drive is labeled with the drive letter C, because it is the first available drive letter for hard drives. The computer reserves the A: and B: drive letters for the floppy disk drive and removable media, such as tape drives,...

Why is'this'an R-value in C++?

In the early version of C++ would let ‘this’ pointer to be changed; by doing so a programmer could change which object a method was working on. This feature was eventually removed, and now this in C++ is an r-value.

Why learning C programming is a must?

Why learning C Programming is a must? C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and 1973. It was mainly developed as a system programming language to write operating system.

Why do drives start from c?

Why Not A Or B? Why Do Drives Start From C? The various logical drives in Windows are assigned a drive letter. Generally, the drive letter for the first logical drive is C followed by D, E, F. Well, A and B are also alphabets but Windows reserves these drive letters for some special purpose, which is floppy drives.


2 Answers

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.

like image 69
Luca Avatar answered Nov 12 '22 17:11

Luca


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.

like image 22
Steck Avatar answered Nov 12 '22 16:11

Steck