0

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.

Hermanto
  • 552
  • 6
  • 15
  • 1
    It’s valid C# - 7 something?. Have a ‘fiddle’ link? Maybe it’s using an older C# language target (6? earlier 7?) that does support the “assignment” syntax (and *naught* with the trailing comma). – user2864740 Oct 29 '19 at 04:55
  • @user2864740 I think I'm using C# 6, since the installed .NET on my computer is 4.6.1. Fiddle link is provided on the question, or please visit this [https://dotnetfiddle.net/131Nvm] (link). – Hermanto Oct 29 '19 at 05:00
  • [Don't confuse .NET Framework versions with C# versions](https://stackoverflow.com/q/247621/8967612). – 41686d6564 stands w. Palestine Oct 29 '19 at 05:06
  • That dictonary initializer is available from C#6. The .Net Framework is not related to the C# version. The comma appended to the last element is ignored. – Jimi Oct 29 '19 at 05:07
  • @peter-duninho, Oops, I didn't find the question. Thank you for pointing me. – Hermanto Oct 29 '19 at 05:08

1 Answers1

0
  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.
dotNET
  • 33,414
  • 24
  • 162
  • 251