1

I've wrote this small program in C#

private void Form1_Load(object sender, EventArgs e)
{
    MessageBox.Show(("7797302D875A8922EBFC7DECBD352FE88F35642F" == "‎7797302D875A8922EBFC7DECBD352FE88F35642F").ToString());

    var a = "7797302D875A8922EBFC7DECBD352FE88F35642F";
    var b = "7797302D875A8922EBFC7DECBD352FE88F35642F";
    MessageBox.Show((a == b).ToString());

}

First messageBox shows "False" while Messagebox shows "True".

My question is: why can I not compare the two strings with the == operator?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Jens Borrisholt
  • 6,174
  • 1
  • 33
  • 67
  • 3
    Probably a copy&paste error. – CodesInChaos Jan 20 '15 at 12:13
  • possible duplicate of [Are string.Equals() and == operator really same?](http://stackoverflow.com/questions/3678792/are-string-equals-and-operator-really-same) – Gerald Versluis Jan 20 '15 at 12:15
  • possible duplicate of [C# .Equals(), .ReferenceEquals() and == operator](http://stackoverflow.com/questions/3869601/c-sharp-equals-referenceequals-and-operator) – Rohit Prakash Jan 20 '15 at 12:16
  • 5
    The `==` operator works just fine for strings. It's your second string literal that contains an invisible character at position 0, so it differs from the first string. – Pieter Witvoet Jan 20 '15 at 12:18
  • 1
    Also `"7797302D875A8922EBFC7DECBD352FE88F35642F".Length == 40 && "‎7797302D875A8922EBFC7DECBD352FE88F35642F".Length == 41` – knittl Jan 20 '15 at 12:19

2 Answers2

10

Your second string has invisible Left-to-right mark character as (U+200E).

Looks like just another copy-paste issue.

enter image description here

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 2
    It might be important to note that you actually can use the `==` operator for strings. – Tim Schmelter Jan 20 '15 at 12:18
  • @TimSchmelter Exactly. I didn't mentioned in my answer because this question already linked/closed as duplicate with http://stackoverflow.com/q/3678792/447156 and http://stackoverflow.com/q/814878/447156 in comments section. Also he can check it from [reference source](http://referencesource.microsoft.com/#mscorlib/system/string.cs,673) as well about how `==` overloaded for strings. – Soner Gönül Jan 20 '15 at 12:30
  • Thank you for your answer. Some how I didn't think of that my self :D – Jens Borrisholt Jan 20 '15 at 12:31
3

The difference isn't caused by the comparison, but your test string strings.

The second string of the first case starts with the invisible 0x200E, the unicode left-to-right mark.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262