Why NameValueCollection instance initialization still compiles with extra comma?

201 Views Asked by At

I am using NameValueCollection to store values that I will post to API server later. Today I accidentally added extra comma when I initialize an instance of NameValueCollection like simple code below:

NameValueCollection nvc = new NameValueCollection()
{
    ["foo"] = "bar",
    ["hello"] = "world", // <-- an extra comma here
};

Note that there is extra comma after world value. This code compiles normally on my computer and other dev's computer, with or without extra comma. But I can't manage it to run on .NET Fiddle even using the right code. I'm using .NET 4.6.1 if it matters.

I am aware of different way to initialize NameValueCollection like on fiddle above, but it's not the problem/question. My question is, why can the compiler compile this broken code and not issue some warning? Or maybe my Visual Studio settings are incorrect in somewhere? Or I am missing some coding principle? Please advice. Thank you.

1

There are 1 best solutions below

0
dotNET On
  1. This is not specific to NameValueCollection, all collection types as well as Enums allow this.
  2. This has got nothing to do with .NET Framework version. This is a C# compiler feature.
  3. This makes programmer's life easier. If you get a chance to work in PHP/JS, this feels like a welcome little feature.
  4. You can read more details about it in this excellent SO post.