Search code examples
c#string-comparison

String comparision not working correctly?


I'm using this library to hook keys and I have some problems with comparing e.KeyCode.ToString() with same string.

I have variable which is string equivalent of

Keys.Oemtilde -> Program.KeyboardTradeHotkey = "Oemtilde";

I keep it in string because I read that string from xml file and I can't seem to get any way to convert string to Keys.

If i use it this way:

            if (e.KeyCode.Equals(Keys.Oemtilde)) {
                    Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
            } else {
                // failed to catch - executes else 
                Logging.AddToLog("[Keyboard][PRESS]");
            }

It works fine and: Logging.AddToLog("[Keyboard][Check] " + e.KeyCode); is executed.

If i use it:

            if (e.KeyCode.ToString() == Program.KeyboardTradeHotkey) {
                    Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
            } else {
                // failed to catch - executes else 
                Logging.AddToLog("[Keyboard][PRESS]");
            }

It executes else clause. It seems like String Compare doesn't really works in this case even thou both string (e.KeyCode.ToString() and Program.KeyboardTradeHotkey are the same.

What can be the reason for this?


Solution

  • I think it is because KeyCode.ToString() doesn't return what you expect it to return. Look at the view in a Watch.