Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline property initialisation and trailing comma

void Main()
{
    Test t = new Test
    {
        A = "a",
        B = "b", // <-- erroneous trailing comma
    };
}

public class Test
{
    public string A { get; set; }
    public string B { get; set; }
}

I find the above typo in my code quite a lot. I'm always suprised that the compiler doesn't seem to care about this. Why is the above not a syntax errror? Is there any actually valid use for it?

like image 984
fearofawhackplanet Avatar asked Mar 09 '11 11:03

fearofawhackplanet


People also ask

What is a trailing comma?

A trailing comma, also known as a dangling or terminal comma, is a comma symbol that is typed after the last item of a list of elements. Since the introduction of the JavaScript language, trailing commas have been legal in array literals. Later, object literals joined arrays.

Is trailing commas allowed in JavaScript?

JavaScript has allowed trailing commas in array literals since the beginning. Trailing commas are now also allowed in object literals, function parameters, named imports, named exports, and more.


2 Answers

I find the above typo in my code quite a lot. I'm always suprised that the compiler doesn't seem to care about this. Why is the above not a syntax errror?

Because the people designing the C# syntax grammar were smart enough to learn the lessons from other programming languages which didn't allow the dangling comma, to the constant irritation of programmers in those languages.

For example, ECMAScript (JavaScript) was silent on the issue initially, and so naturally some implementations (SpiderMonkey in Firefox, Opera's JavaScript, etc.) allowed them while others (Microsoft's JScript) didn't. And so this led to a spate of "why doesn't this work in IE" questions here and elsewhere. (Fortunately, ECMAScript 5 explicitly allows them, and IE8 finally supports them in object initializers -- IE8 still treats array initializers in a non-standard way, though to be fair the dangling comma for those was only clarified in ECMAScript 5, too.)

You find this in lots of other places in the C# grammar too, like enums and array initializers.

like image 138
T.J. Crowder Avatar answered Oct 23 '22 11:10

T.J. Crowder


It's not an error because it's convenient. To add to the initializer, you only have to add in one line instead of adding a comma to one line and entering a whole new line.

This is actually fairly common in list/array initialization in other languages too (Python, Ruby, Haskell come to mind).

like image 6
Mark Rushakoff Avatar answered Oct 23 '22 11:10

Mark Rushakoff