What is the difference between using String.Equals (str1, str2) and str1 == str2

Possible duplicate:
C # difference between == and .Equals ()

I use a lot of them in my daily code processing program, but I don’t really know how much they differ from each other.

 if(String.Equals(str1, str2)) 

and

 if(str1 == str2) 
+7
source share
2 answers

(UPDATE)

They are actually exactly the same.

 public static bool operator ==(string a, string b) { return Equals(a, b); } 

therefore == calls Equals .


 public static bool Equals(string a, string b) { return ((a == b) || (((a != null) && (b != null)) && EqualsHelper(a, b))); } 

EqualsHelper is an unsafe method:

UPDATE What it does is iterates over the characters using integer pointers and compares them as integers (4 bytes at a time). He does this 10 at a time, and then one at a time.

 private static unsafe bool EqualsHelper(string strA, string strB) { int length = strA.Length; if (length != strB.Length) { return false; } fixed (char* chRef = &strA.m_firstChar) { fixed (char* chRef2 = &strB.m_firstChar) { char* chPtr = chRef; char* chPtr2 = chRef2; while (length >= 10) { if ((((*(((int*) chPtr)) != *(((int*) chPtr2))) || (*(((int*) (chPtr + 2))) != *(((int*) (chPtr2 + 2))))) || ((*(((int*) (chPtr + 4))) != *(((int*) (chPtr2 + 4)))) || (*(((int*) (chPtr + 6))) != *(((int*) (chPtr2 + 6)))))) || (*(((int*) (chPtr + 8))) != *(((int*) (chPtr2 + 8))))) { break; } chPtr += 10; chPtr2 += 10; length -= 10; } while (length > 0) { if (*(((int*) chPtr)) != *(((int*) chPtr2))) { break; } chPtr += 2; chPtr2 += 2; length -= 2; } return (length <= 0); } } } 
+6
source

They are exactly the same. Here is what ildasm shows for ==

  IL_0002: call bool System.String::Equals(string, string) 

Also read the documentation: http://msdn.microsoft.com/en-us/library/system.string.op_equality.aspx It says:

This statement is implemented using the Equals method.

+2
source

All Articles