views:

233

answers:

3

System.Collections.Specialized.NameObjectCollectionBase has two similar properties:

  string[] AllKeys
  NameObjectCollectionBase.KeyCollection Keys

Do they provide different sets of data? When would I want to use one over the other?

+10  A: 

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
Neil Williams
That's what I'm thinking too. You'd sure think a big difference like that would be explicit in the documentation. (Or maybe named a little better to reflect the semantics). Usually, the MSDN documentation is pretty excellent about things like that. That's why this one threw me off-guard.
MojoFilter
+1 good test to prove the point.
BFree
Agreed, bad name and unclear semantics. Not to mention FxCop dislikes properties returning arrays for this very reason! Since this class is a leftover from the pre-generics days, perhaps Dictionary<string, string> or Dictionary<string, YourType> would be better now?
Neil Williams
+2  A: 

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.

BFree
+1  A: 

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.

Krypes