157 recommendations for writing high-quality code to improve C # programs--recommendation 11: Treat = = and equals differently

Source: Internet
Author: User

Recommendation 11: Treat = = and equals differently

Before starting this recommendation, it is first to clarify the concept of "equality". The CLR divides equality into two categories: value equality and reference equality. If the two variables used to compare have equal values, define them as "value equality", and if the two variables that are compared refer to the same object in memory, define it as "referential equality."

Both the operator "= =" and the method "Equals" tend to express such a principle:

    • For value types, you should return true if the values of the type are equal.
    • Returns true for reference types if the type points to the same object.

The following code output follows the above principles:

    Static voidvaluetypeopequals () {inti =1; intj =1; //TrueConsole.WriteLine (i = =j); J=i; //TrueConsole.WriteLine (i = =j); }           Static voidreferencetypeopequals () {ObjectA =1; Objectb =1; //FalseConsole.WriteLine (A = =b); b=A; //TrueConsole.WriteLine (A = =b); }           Static voidvaluetypeequals () {inti =1; intj =1; //TrueConsole.WriteLine (I.equals (j)); J=i; //TrueConsole.WriteLine (I.equals (j)); }            Static voidreferencetypeequals () {ObjectA =NewPerson ("NB123"); Objectb =NewPerson ("NB123"); //FalseConsole.WriteLine (a.equals (b)); b=A; //TrueConsole.WriteLine (a.equals (b)); } 

However, we also need to understand that either the operator "= =" or "Equals" methods can be overloaded. For example, for a special reference type such as String, Microsoft finds its practical significance closer to the value type, so in the FCL, the comparison of string is overloaded to a comparison of "value of type", not to "reference itself".

Many custom types, especially custom reference types, are designed to have a situation that is closer to the string type. As in the example of the type of person, in real life, if the two idcode is equal, we think the two are the same people, this time, it is necessary to overload equals this method, the code is as follows:

    classPerson { Public stringIdcode {Get;Private Set; }  PublicPerson (stringIdcode) {               This. Idcode =Idcode; }                Public Override BOOLEquals (Objectobj) {              returnIdcode = = (obj asPerson ).          Idcode; }      } 

At this point, by using equals to compare the values of two person objects with the same Idcode, the return is true, and the code looks like this:

    Object New Person ("NB123");       Object New Person ("NB123");       // False      Console.WriteLine (A = = b)      ; // True      

Here, the difference between the operator "= =" and the "Equals" method is raised. In general, for reference types, we want to define "value equality," which should only be overloaded with the Equals method, and "= =" to mean "referential equality."

Note Because the operator "= =" and "Equals" methods can be overloaded to represent "value equality" and "referential equality" from the syntax implementation. So, to make sure there is a way of definitely comparing "referential equality", an object is provided in the FCL. ReferenceEquals method. This method compares: Two examples are the same example.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--recommendation 11: Treat = = and equals differently

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.