Rewrite Rules and usage of equals () and operator =

Source: Internet
Author: User

C # has two different types of equality: the reference equality and the value are equal. Equality of values is commonly understood as equal: it means that two objects contain the same value. For example, two integers with a value of 2 have equal values. Referencing equal means that not two objects are to be compared, but two objects are referenced, and the two references the same object. This can be achieved through simple assignment, as shown in the following example:

C #
System.Object a = new System.Object();System.Object b = a;System.Object.ReferenceEquals(a, b);  //returns true

In the code above, only one object exists, but multiple references to this object exist: A and B. Since they reference the same object, they have reference equality. If two objects have reference equality, they also have value equality, but the value equality cannot guarantee the reference equality.

To check the equality of reference, use referenceequals. To check the equality of values, use equals.

In summary, the following usage methods can be obtained: 1. For the reference type. To determine whether the references are equal, use the referenceequals method or the = Operator. If the values are equal, rewrite the equal method, it is best to use the equal static method of the type (eliminating null judgment ). 2. For the value type. The default equal method and = operator are both comparison values, which can meet most of the requirements (if the value type contains referenced member variables, You need to override the equal method ); the referenceequals method always returns false in the value type (because of packing/unpacking ).

 

 

Rewrite operator =

By default, operator = checks whether two references indicate the same object to test whether the references are equal. Therefore, you do not need to implement the = Operator to obtain the reference type. When the type is immutable (that is, the data contained in the instance cannot be changed), it may be useful to compare whether the value is equal by using the overload operator =, rather than comparing whether the reference is equal, as an unchangeable object, as long as its value is the same, it can be treated as the same. We recommend that you do not override operator = in a non-Immutable type.

The overloaded operator = implementation should not cause exceptions. Any type of overload operator = should also be reloaded! =. For example:

C #
//add this code to class ThreeDPoint as defined previously//public static bool operator ==(ThreeDPoint a, ThreeDPoint b){    // If both are null, or both are same instance, return true.    if (System.Object.ReferenceEquals(a, b))    {        return true;    }    // If one is null, but not both, return false.    if (((object)a == null) || ((object)b == null))    {        return false;    }    // Return true if the fields match:    return a.x == b.x && a.y == b.y && a.z == b.z;}public static bool operator !=(ThreeDPoint a, ThreeDPoint b){    return !(a == b);}

Note:

Common Errors in the overload of operator = are to use (a = B), (a = NULL), or (B = NULL) to check the equality of reference. This will call the overloaded operator =, resulting in an infinite loop. Use referenceequals or forcibly convert the type to object to avoid infinite loops.

Override equals

Since equals is a virtual method, any class can override its implementation. Any class that indicates a value (essentially any value type) or a group of values (such as a plural class) should be overwritten.Equals. If the type is icomparable, it should be overwritten.Equals.

EqualsThe new implementation should follow all the guarantees of equals:

  • X.Equals(X) returns true.

  • X.Equals(Y) and Y.Equals(X) returns the same value.

  • If (X.Equals(Y) & Y.Equals(Z) returns true, then X.Equals(Z) returns true.

  • As long as the objects referenced by X and Y are not modified.Equals(Y) will return the same value for subsequent calls.

  • X.Equals(Null) returns false (only non-null. For more information, see the empty type (C # programming guide ).)

EqualsThe new implementation of should not cause exceptions. Rewrite is recommended.EqualsAny class of also overwrites object...:. gethashcode. Besides implementationEqualsIn addition to (object), we recommend that all classes be their own type implementations.Equals(Type) to enhance performance. For example:

C #
class TwoDPoint : System.Object{    public readonly int x, y;    public TwoDPoint(int x, int y)  //constructor    {        this.x = x;        this.y = y;    }    public override bool Equals(System.Object obj)    {        // If parameter is null return false.        if (obj == null)        {            return false;        }        // If parameter cannot be cast to Point return false.        TwoDPoint p = obj as TwoDPoint;        if ((System.Object)p == null)        {            return false;        }        // Return true if the fields match:        return (x == p.x) && (y == p.y);    }    public bool Equals(TwoDPoint p)    {        // If parameter is null return false:        if ((object)p == null)        {            return false;        }        // Return true if the fields match:        return (x == p.x) && (y == p.y);    }    public override int GetHashCode()    {        return x ^ y;    }}

Callable base classEqualsAny derived class of should do so before completing its comparison. In the following example,EqualsCall base classEqualsThe latter checks the null parameter and compares the parameter type with the type of the derived class. In this way, the task of checking the new data fields declared in the derived class is left toEqualsImplementation:

C #
class ThreeDPoint : TwoDPoint{    public readonly int z;    public ThreeDPoint(int x, int y, int z)        : base(x, y)    {        this.z = z;    }    public override bool Equals(System.Object obj)    {        // If parameter cannot be cast to ThreeDPoint return false:        ThreeDPoint p = obj as ThreeDPoint;        if ((object)p == null)        {            return false;        }        // Return true if the fields match:        return base.Equals(obj) && z == p.z;    }    public bool Equals(ThreeDPoint p)    {        // Return true if the fields match:        return base.Equals((TwoDPoint)p) && z == p.z;    }    public override int GetHashCode()    {        return base.GetHashCode() ^ z;    }}

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.