Amit Soni
Amit Soni

Reputation: 3316

HttpValueCollection and NameValueCollection

What is the difference between HttpValueCollection and NameValueCollection?
If possible please explain with example.

Thanks

Upvotes: 36

Views: 18482

Answers (2)

Jatin Sanghvi
Jatin Sanghvi

Reputation: 2243

One point that is not obvious in Darin's answer is that NameValueCollection does not override ToString() method, while HttpValueCollection overrides it. This particular property and implicit URL encoding of values makes the latter one a right choice if you want to convert the collection back to query string.

public class Test
{
    public static void Main()
    {
        var httpValueCollection = HttpUtility.ParseQueryString(string.Empty);
        httpValueCollection["param1"] = "value1";
        httpValueCollection["param2"] = "value2";
        Console.WriteLine(httpValueCollection.ToString());

        var nameValueCollection = new NameValueCollection();
        nameValueCollection["param1"] = "value1";
        nameValueCollection["param2"] = "value2";
        Console.WriteLine(nameValueCollection.ToString());  
    }
}

Outputs:

param1=value1&param2=value2
System.Collections.Specialized.NameValueCollection

Upvotes: 10

Darin Dimitrov
Darin Dimitrov

Reputation: 1039228

NameValueCollection is case sensitive for the keys, HttpValueCollection isn't. Also HttpValueCollection is an internal class that derives from NameValueCollection that you are never supposed to use directly in your code. Another property of HttpValueCollection is that it automatically url encodes values when you add them to this collection.

Here's how to use the HttpValueCollection class:

class Program
{
    static void Main()
    {
        // returns an implementation of NameValueCollection
        // which in fact is HttpValueCollection
        var values = HttpUtility.ParseQueryString(string.Empty);
        values["param1"] = "v&=+alue1";
        values["param2"] = "value2";*

        // prints "param1=v%26%3d%2balue1&param2=value2"
        Console.WriteLine(values.ToString());
    }
}

Upvotes: 57

Related Questions