String.Equals vs String.Compare vs “==” in Action. Explanation needed

前端 未结 4 975
半阙折子戏
半阙折子戏 2021-02-20 06:59

Following is the code snippet from a console application -

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

              


        
4条回答
  •  野性不改
    2021-02-20 08:01

    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.

提交回复
热议问题