Can I use collection initializers with a NameValueCollection?

C#Collections

C# Problem Overview


Is there a way to initialize a NVC using C# collection initializer syntax:

NameValueCollection nvc = new NameValueCollection() { ("a", "1"), ("b", "2") };

Thanks

C# Solutions


Solution 1 - C#

Yes; just uses braces instead of parentheses.

var nvc = new NameValueCollection { {"a", "1"}, {"b", "2"} };

You can call Add methods with arbitrary sets of parameters using the syntax.

Solution 2 - C#

You can use collection initializers with everything that has Add method. Yeah, duck typing. If Add has more then 1 param put tuples in curly bracets:

NameValueCollection nvc = new NameValueCollection() { { "a", "1" }, { "b", "2" } };

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongapView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#AndreyView Answer on Stackoverflow