Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the compiler not complaining about an additional ',' in Array or Object Initializers?

Tags:

c#

c#-3.0

c#-4.0

Using simple type like

class A {
  public int X, Y;
}

with object intializers, one can write

var a = new A { X=0, Y=0 };

But the following is also accepted by the compiler:

var a = new A { X=0, Y=0, }; // notice the additional ','

Same for int[] v = new int[] { 1, 2, };

This looks a bit strange ... Did they forgot to reject the additional ',' in the compiler or is there a deeper meaning behind this?

like image 334
Danvil Avatar asked Apr 20 '10 10:04

Danvil


2 Answers

There isn't anything deep, it's a common thing accepted by compilers of many (but not all) languages. This makes doing lists easier:

var a = new A {
    X = 0,
    Y = 0,
};

When you want to add Z = 0, you don't need to edit the previous line to add a comma. This improves source code control deltas, because there is only one new line instead of one new line and one changed line.

like image 137
Greg Hewgill Avatar answered Sep 29 '22 20:09

Greg Hewgill


This also simplifies an implementation of code generators. They don't have to check the last comma.

like image 40
n535 Avatar answered Sep 29 '22 20:09

n535