Dictionary.ContainsKey StringComparer.Ordinal

2.9k views Asked by At

I'm working with a Dictionary in C# with .NET 3.5. I've created a Dictionary<string, int> object and passed in the StringComparer.Ordinal equality comparer. When I do the following code, however, I don't get what I would expect:

Dictionary<string, int> theDictionary = new Dictionary<string, int>(StringComparer.Ordinal);
theDictionary.Add("First", 1);
bool exists = theDictionary.ContainsKey("FIRST");    // equals true, when it should not

What am I not seeing here?

1

There are 1 answers

1
agent-j On

Are you sure you didn't use StringComparer.OrdinalIgnoreCase?

This code prints false for me with C# v3.5 compiler:

using System;
using System.Collections.Generic;

    static class Program
    {
      static void Main()
      {
        Dictionary<string, int> theDictionary = new Dictionary<string, int>(StringComparer.Ordinal);
        theDictionary.Add("First", 1);
        bool exists = theDictionary.ContainsKey("FIRST");

        Console.WriteLine(exists);
      }
    }