Khoa Wilson
Khoa Wilson

Reputation: 43

Dictionary.ContainsKey return false even thought the key exists

I have piece of code as below:

IDictionary<string, string> dictionary = new Dictionary<string, string>(){
        { "de-DE", "German"},
        { "en‐GB", "English"},
        { "en‐US", "English"},
        { "es‐ES", "Spanish"},
        { "es‐MX", "Spanish"},
        { "fr‐CA", "French"},
        { "fr‐FR", "French"},
        { "hu‐HU", "Hungarian"},
        { "pl‐PL", "Polish"},
        { "pt‐PT", "Portuguese"},
        { "nl‐NL", "Dutch"},
        { "nb‐NO", "Norwegian"},
        { "sv‐SE", "Swedish"},
        { "it‐IT", "Italian"},
};
bool check = dictionary.ContainsKey("en-US");
Console.WriteLine(check);

The check returns false. Could someone help to explain it?

Upvotes: 4

Views: 652

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39956

As pointed already Your dashes aren't the same. I have added another item to your Dictionary that gives you the expected result and compare the underlying IL, by Ildasm to know the difference:

{ "en‐US", "English"},
{ "en-US", "English2"},

And:

IL_002d:  nop
IL_002e:  dup
IL_002f:  ldstr      bytearray (65 00 6E 00 10 20 55 00 53 00 )                   // e.n.. U.S.
IL_0034:  ldstr      "English"
IL_0039:  callvirt   instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string,string>::Add(!0,
                                                                                                                 !1)
IL_003e:  nop
IL_003f:  dup
IL_0040:  ldstr      "en-US"
IL_0045:  ldstr      "English2"
IL_004a:  callvirt   instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string,string>::Add(!0,
                                                                                                                 !1)

enter image description here

Upvotes: 2

James Hill
James Hill

Reputation: 61802

Your dashes aren't the same. Take a look at what your text looks like in Notepad++ (useful when you need to debug character related stuff like this):

After replacing your dash with an actual -, the code works as expected.

enter image description here

EDIT

Thanks, @Scott Chamberlain for the .net fiddle that highlights the character differences.

Upvotes: 6

Related Questions