Equality comparison of objects in. Net (C #)

Source: Internet
Author: User

I have never been concerned about this issue before and was asked by someone else. (from csdn)

After discussing operators and briefly introducing equal operators, we should consider what they mean when processing classes and structure instances are equal. Understanding the mechanism of object equality comparison is very important for compiling logical expressions. In addition, it is also important to implement Operator Overloading and data type conversion. Operator Overloading will be discussed later in this chapter.

The mechanism of equal object comparison is different for the comparison of reference type (instance of the class) and value type (basic data type, structure or enumeration instance. The following describes the comparison between the equal types of the reference type and the value type.

5.3.1 comparison of equal reference types

One surprising aspect of system. object is that it defines three different methods to compare the equality of objects: referenceequals () and equals. When we add the comparison operator =, there are actually four equal comparison methods. There are some subtle differences between these methods. The following describes these methods.

1. referenceequals () method

Referenceequals () is a static method to test whether two references point to the same instance of the class, that is, whether the two references contain the same address in the memory. As a static method, it cannot be rewritten, so it can only use the implementation code of system. object. If the two references point to the same object instance, referenceequals () always returns true; otherwise, false is returned. But it considers null to be null:

Someclass X, Y;

X = new someclass ();

Y = new someclass ();

Bool b1 = referenceequals (null, null); // return true

Bool b2 = referenceequals (null, x); // return false

Bool B3 = referenceequals (x, y); // return false because X and Y

// Point to different objects

2. Virtual equals () method

The system. Object implementation code of the virtual version of equals () is also referenced. But because this method is virtual, you can rewrite it in your own class and compare objects by value. Especially if you want the instance of the class to be used as the key in the dictionary, you need to override this method to compare the value. Otherwise, according to the method of rewriting object. gethashcode (), the dictionary class containing the object either does not work or is very inefficient. When rewriting the equals () method, note that the code to be rewritten will not throw an exception. This is because if an exception is thrown, the dictionary class may have problems. Some. net base classes that call this method internally may also have problems.

3. Static equals () method

The static version of equals () has the same effect as the virtual instance version. The difference is that the static version has two parameters and they are compared equally. This method can handle the condition that one of the two objects is null. Therefore, if an object may be null, this method can throw an exception and provide additional protection. For a static overloaded version, you must first check whether the reference it transfers is null. If they are both null, true is returned (because null is equal to null ). If only one reference is null, false is returned. If both references point to an object, it calls the virtual instance version of equals. This means that when you override the instance version of equals (), the effect is equivalent to rewriting the static version.

4. comparison operator =

It is better to regard the comparison operator as an intermediate option between strict Value Comparison and strict reference comparison. In most cases, the following code:

Bool B = (x = y); // X, Y object references

Compare reference. However, if you think of some classes as values, their meanings will be more intuitive. In these cases, it is best to rewrite the comparison operator to execute the comparison of values. The reload of operators will be discussed later, but it is clear that one of its examples is the system. string class. Microsoft has rewritten this operator to compare the content of strings rather than their references.

5.3.2 comparison of equal value types

When comparing values of the same type, use the same rule as the reference type: referenceequals () is used to compare references, equals () is used to compare values, and comparison operators can be considered as an intermediate item. But the biggest difference is that value types must be boxed to convert them into references before they can be executed. In addition, Microsoft has already overloaded the instance method equals () in the system. valuetype class to perform an appropriate equality test on the value type. If you call SA. equals (SB), where SA and Sb are instances of a certain structure, return true or false based on whether SA and SB contain the same value in all its fields. On the other hand, by default, the = Operator cannot be overloaded on its own structure. Using (SA = SB) in an expression causes a compilation error, unless the = overloaded version is provided for the structure in the code.

In addition, when applying referenceequals () to the value type, false is always returned, because in order to call this method, the value type needs to be packed into the object. Even if you use the following code:

Bool B = referenceequals (V, V); // v is a variable of some value type

It also returns false, because when converting each parameter, V is packed separately, which means different references are obtained. Calling referenceequals () to compare value types actually makes no sense.

Although the equals () default overload provided by system. valuetype must be sufficient for most custom structures, you can rewrite it for your own structure to improve performance. In addition, if the value type contains the reference type of the field, you need to override equals () to provide proper semantics for these fields, because equals () by default, only their addresses are compared.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.