String.Equals vs String.Compare vs "==" in Action. Explanation needed

Subhasis picture Subhasis · Jun 17, 2015 · Viewed 7.2k times · Source

Following is the code snippet from a console application -

class MyClass
{        
   public int GetDay(string data22)
    {
        int returnValue = 0;

        if (string.Compare(data22,"THURSDAY") == 0) // true
        {
            returnValue = (int)DayOfWeek.Thursday;
        }

        if (data22 == "THURSDAY") //false
        {
            returnValue = (int)DayOfWeek.Thursday;
        }

        if (string.Equals(data22, "THURSDAY"))//false
        {
            returnValue = (int)DayOfWeek.Thursday;
        }
        return returnValue;
    }
}

class Program
{
    static void Main(string[] args)
    {
        string ExecutionDay = "‎THURSDAY";
        MyClass obj1 = new MyClass();
        int MyDays = obj1.GetDay(ExecutionDay);
    }
}

Question is - Why does the first comparison (string.compare) work and the other two comparison methods does not work in THIS PARTICULAR CASE ?

Answer

Yuval Itzchakov picture Yuval Itzchakov · Jun 17, 2015

Why does the first comparison (string.compare) work and the other two comparison methods does not work in THIS PARTICULAR CASE

There are invisible characters (particularly, a Left-to-Right mark (Thanks @MatthewWatson)) in your code. You can view them with any hex editor:

enter image description here

This is over-looked by string.Compare, while it isn't with string.Equals. You can see it in the docs:

Notes to Callers:

Character sets include ignorable characters. The Compare(String, String) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the .NET Framework 4 or later, a culture-sensitive comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.