Wednesday, July 1, 2026

C# NameValueCollection comapred with generic Dictionary

In this post, we wiil see:
  • How is NameValueCollection different from Dictionary? 
  • When to use NameValueCollection?
First look at the following example of NameValueCollection.
Example
using System.Collections.Specialized;
public class Program
{
    public static void Main()
    {
        // Creates and initializes a new NameValueCollection.
        NameValueCollection myCol = new NameValueCollection();
        myCol.Add("red", "Rose");
        myCol.Add("green", "Flag");
        myCol.Add("blue", "Sky");
        myCol.Add("blue", "Sky Blue");
        myCol.Add("blue", "Navy Blue");
        myCol.Add(null, "Null key");

        Console.WriteLine("Count: {0}", myCol.Count);
        foreach (string? k in myCol.AllKeys)
        {
            Console.WriteLine("Key:{0} Value:{1}", k, myCol[k]);
        }
        Console.ReadKey();
    }

}
/*
OUTPUT
Count: 3
Key: red Value:Rose
Key:green Value:Flag
Key:blue Value:Sky, Sky Blue, Navy Blue
Key: Value:Null key
*/

The above example code actually perfectly demonstrates the biggest fundamental difference between the two!

Notice the "blue" key is added three times? Instead of throwing an error or overwriting the old value, it combined them into a single, comma-separated string ("Sky, Sky Blue, Navy Blue"). A standard Dictionary would never let you get away with that.

Here is a breakdown of how NameValueCollection differs from Dictionary<TKey, TValue> and exactly when you should use it.

Key Differences

Feature NameValueCollection Dictionary<string, string>
Duplicate Keys Allowed. Automatically joins multiple values under the same key with a comma. Not Allowed. Will throw an exception on .Add() or overwrite the value if using the indexer dict[key] = value.
Type Safety Strictly string only for both keys and values. Generic. Can use any types (e.g., Dictionary<int, Customer>).
Access Methods Can look up values by Key (string) OR by Index (integer). Can only look up values by Key.
Performance Slower. It is an older, non-generic collection (legacy System.Collections.Specialized). Faster. Highly optimized for hash-lookups and avoids boxing/unboxing.
Null Keys Allowed. You can have a null key holding values. Not Allowed. Will throw an ArgumentNullException.

Internal Structure Contrast

Under the hood, NameValueCollection handles duplicate keys by managing an array of strings for each key, which it flattens when you use the default string indexer.

NameValueCollection Structure:

[ "red" ]   ---> [ "Rose" ]

[ "green" ] ---> [ "Flag" ]

[ "blue" ]  ---> [ "Sky", "Sky Blue", "Navy Blue" ]  <-- (Flattens to "Sky,Sky Blue,Navy Blue")

When to use NameValueCollection?

In modern .NET development, Dictionary<TKey, TValue> (or ILookup<TKey, TValue>) is the default choice. However, NameValueCollection is still the right tool for specific scenarios:

1. Handling HTTP Query Strings and Headers

The web inherently allows duplicate keys in URLs (e.g., ?tag=csharp&tag=dotnet&tag=collections). NameValueCollection is uniquely suited for this, which is why legacy ASP.NET used it heavily for Request.QueryString and Request.Headers.

2.Legacy .NET Configuration Files

Older .config files (app.config / web.config) store <appSettings> as a NameValueCollection. If you are dealing with legacy configuration APIs, you'll still run into it.

3. When you need both Key and Ordered Index access

If you need to fetch elements both by their string identifier and by their numerical insertion order (myCol[0]), NameValueCollection supports this out of the box.

Modern Alternatives to Keep in Mind

If you need to map one key to multiple values in modern C# without using an old, string-only collection, consider:

  • Dictionary<string, List<string>>: Gives you strict generic type safety, but you have to write the boilerplate code to initialize the inner list for new keys.
  • ILookup<TKey, TElement>: Created via LINQ (.ToLookup()). Great for multi-value groups, but it is immutable once created.

 

No comments:

Post a Comment

Hot Topics