What is the difference between the properties Keys and AllKeys on a NameValueCollection?

AllKeys is an O(n) operation, while Keys is O(1). This is because AllKeys copies the keys into a new array, while Keys just returns a reference to NameValueCollection's private key collection. So beyond the difference in performance, the collection returned by Keys will change with the base collection as it's just a reference to the original, while AllKeys will be insulated from the changes because it's a copy.

This little test program shows the difference in behavior:

using System;
using System.Collections.Specialized;

static class Program
{
    static void Main()
    {
        var collection = new NameValueCollection();

        var keys = collection.Keys;
        var allKeys = collection.AllKeys;

        collection.Add("Name", "Value");

        Console.WriteLine("Keys: " + keys.Count);
        Console.WriteLine("AllKeys: " + allKeys.Length);
        Console.ReadLine();
    }
}

The output is:

Keys: 1
AllKeys: 0

According to MSDN's documentation, when using AllKeys, it's O(n) to retrieve all the values, whereas when using Keys it's O(1).

Keys

Retrieving the value of this property is an O(1) operation

AllKeys

This method is an O(n) operation, where n is Count.

So basically, it seems that Keys has better performance.


there however is the added benefit that you would be able to do operations on your collection using a foreach or a LINQ statement on the return of AllKeys(). Since its a copy, you won't get errors modifying a list currently being enumerated.