Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary.ContainsKey return false even thought the key exists

Tags:

c#

dictionary

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?

like image 519
Khoa Wilson Avatar asked Jan 29 '23 16:01

Khoa Wilson


1 Answers

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.

like image 121
James Hill Avatar answered Feb 02 '23 10:02

James Hill