This section was taken from msdn and was found only when a bug was called to a friend yesterday. Record + share it.
The equals method is only a virtual method defined in system. object. It is overwritten by any class that chooses to execute the task. = Operator is an operator that can be overloaded by a class. This class usually has a constant behavior.
For reference types that are not overloaded with =, this operator compares whether two reference types reference the same object, which happens to be the work of The equals implementation in system. object.
For value types that are not overloaded with =, this operator checks whether the two values are "bitwise" equal, that is, whether each field in the two values is equal. This still happens when you call equals for the value type. However, this implementation is provided by valuetype and compared using reflection, this slows down the implementation of comparison speed bits based on types.
So far, the two are so similar. The main difference between the two is polymorphism. The operator is overloaded rather than overwritten, which means that the compiler only calls the constant version unless it knows the more specific version of the call. To clarify this, see the following example:
Using System;
Public Class Test
{
Static Void Main ()
{
// Create two equal but distinct strings
String A = New String ( New Char [] {'H','E','L','L','O'} );
String B = New String ( New Char [] {'H','E','L','L','O'} );
Console. writeline ( = B );
Console. writeline (A. Equals (B ));
// Now let's see what happens with the same tests
// With variables of type object
Object C = A;
Object D = B;
Console. writeline (C = D );
Console. writeline (C. Equals (d ));
}
}
The result is:
Truetruefalsetrue
The third line is false because the compiler does not know that the C and D content are both string references, so it can only call a non-overloaded version of =. Because they are references to different strings, the constant operator returns false.
So how should we use these operators differently? My principle is: for almost all reference types, use equals when you want to test equality instead of reference consistency. The exception is that string-use = to compare strings makes it much easier, andCodeBetter readability,HoweverYou need to remember that both ends of this operator must be a type string expression to make the comparison normal.
For the value type, I usually use =, because unless the value type itself contains the reference type (which is rare in this case), it is irrelevant to whether the value type is constant or equal.