Difference between == and Equals in C#

Compared:

  1. == is an operator, and Equals is a virtual method in object, which can be rewritten by subclasses;
  2. Equals is generally used to compare whether the contents of two objects are the same after rewriting in subclasses; == without operator overloading: the reference type is used to compare whether the addresses are the same, and the value type is used to compare whether the values ​​are the same.
  3. The operation efficiency is different. Generally, Equals does not have == high efficiency, because generally Equals compares more content than ==;

 Overload Equals:

  1. Declare a method called Equals in the class and mark it as an override of the Equals method of the Object class.

  2. Write custom comparison logic in the overloaded method, usually comparing properties of objects for equality. If the type of the attribute is a value type, you can use the == operator for comparison; if the type of the attribute is a reference type, you need to recursively call the Equals method for comparison.

  3. The overloaded method also needs to handle the case where the incoming parameter is empty or not of the current class type.

Guess you like

Origin blog.csdn.net/HimaRe1/article/details/131110360