Possible Duplicate:
Inline property initialisation and trailing comma
Working on one of my projects (C# 4.0, Visual Studio 2010), I’ve accidentally discovered that code like
var obj = new { field1 = "Test", field2 = 3, }
is compiled and executed OK without any errors or even warnings and works exactly like
var obj = new { field1 = "Test", field2 = 3 }
Why does compiler tolerate the trailing coma in first example? Is this a bug in compiler or such behavior does have some purpose?
Thanks
To determine whether or not it’s a bug in the compiler, you need to look at the C# spec – in this case section 7.6.10.6, which clearly allows it:
So no, it’s not a compiler bug. The language was deliberately designed to allow it.
Now as for why the language has been designed that way – I believe it’s to make it easier to add and remove values when coding. For example:
can become
or
solely by adding or removing a line. This makes it simpler to maintain code, and also easier to write code generators.
Note that this is consistent with array initializers, collection initializers and enums: