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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)