Dictionary Key Case Sensitivity in C#

by Bradley 8. May 2009 16:26

By default you must make sure that a key used to look up a value in a dictionary matches the case of key used to store the value in a dictionary. Simply put, list["A"] would not return the same value as list["a"]. It would be safe to assume that the default behavior was selected for efficiency. After all would you want your code slowed down by doing list["a".ToUpper()], if you knew that the key used to look up a dictionary value would never have a different case than what was used to store it. With that in mind, if case were an issue, most of us would change our code to perform the ToUpper just described. Although this approach is functionally sound, your code could become unnecessarily cluttered. An equally functional approach that would keep your code uncluttered would be to use one of the alternate constructors for your dictionary, see example below.

using System.Collections.Generic;

Dictionary<string, string> list = 
    new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
list.Add("A", "Value");

if (list["A"] != null)
{
    Console.WriteLine("A can be A");
}

if (list["a"] != null)
{
    Console.WriteLine("a can also be A");
}

Tags: , ,

.NET | C#

Powered by BlogEngine.NET 1.5.0.7
Original Theme by Mads Kristensen | Modified by Crafty Coders