Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# allow trailing comma in collection initializers but not in params?

Tags:

syntax

c#

comma

Valid syntax:

var test = new List<string>
{
   "a",
   "b",
   "c",//Valid trailing comma
};

Invalid syntax:

private void Test(params string[] args)
{
}

Test(
   "a",
   "b",
   "c",//Invalid trailing comma
);

Is it a matter of syntax inconsistency or a calculated decision?

like image 213
Den Avatar asked Nov 11 '14 12:11

Den


People also ask

Why does the letter C exist?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.

Does the letter C exist?

C, or c, is the third letter in the English and ISO basic Latin alphabets. Its name in English is cee (pronounced /ˈsiː/), plural cees.

Why does C make 2 sounds?

In the Latin-based orthographies of many European languages, including English, a distinction between hard and soft ⟨c⟩ occurs in which ⟨c⟩ represents two distinct phonemes. The sound of a hard ⟨c⟩ often precedes the non-front vowels ⟨a⟩, ⟨o⟩ and ⟨u⟩, and is that of the voiceless velar stop, /k/ (as in car).


1 Answers

So I'll take a stab at this even though I will never know the "true" reason as I wasn't on the compiler team - and the likelihood of one turning up is questionable.

Trailing commas are generally useful in a few scenarios, namely merging and code-generation. In the context of stuff like collection or property initialisers and enums, leaving a trailing comma is harmless (the compiler can safely infer "end of list" as there is also a closing block bracket it can hook on to.

Method parameters are quite explicit - the compiler needs a lot of control in this area so that it can provide good feedback when people are coding and for other ancillary features. Leaving a trailing comma on method arguments doesn't add any of the value as above and my start to cause confusion over how to handle "incomplete" code (did the user leave it there intentionally or are they just about to type in the next argument?).

You are correct that params fall into the conceptual gap in that you see them as an array, and you can specify them as comma delimited (which was supported prior to collection initialisers). So why do they depart in style from collection initialisers?

The language spec for the params bit doesn't explicitly specify trailing comma support, though it does for collection initialisers for parity towards other languages (C++ I think), which increases familiarity with developers migrating to C# from elsewhere.

My supposition: the fact that it wasn't in spec then causes YAGNI to apply, and from that point forwards the value proposition for the feature is a no-brainer in favour of not implementing it.

like image 132
Adam Houldsworth Avatar answered Oct 14 '22 16:10

Adam Houldsworth