An analysis of example code for "= =" and equals in C #

Source: Internet
Author: User
for "= =" and equals most netizens are summed up like this:

    1. "= =" is a comparison of the values of two variables equal.

    2. Equals is a comparison of two variables that point to the same object.

Such as: This article, and take the example of this article as an example.

public class person{Public person     (string name)     {this         . name = name;     }     public string Name {get; set;}} static void Main (string[] args) {     string a = new string (new char[] {' h ', ' e ', ' l ', ' l ', ' o '});     String b = new string (new char[] {' h ', ' e ', ' l ', ' l ', ' o '});     Console.WriteLine (A = = B);         True     Console.WriteLine (a.equals (b));    True     Object g = A;     Object h = b;     Console.WriteLine (g = = h);         False     Console.WriteLine (g.equals (h));    True person     p1 = new Person ("Jia");     person P2 = new Person ("Jia");     Console.WriteLine (P1 = = p2);       False     Console.WriteLine (P1. Equals (p2));  False person     p3 = new Person ("Jia");     person P4 = p3;     Console.WriteLine (P3 = = p4);       True     Console.WriteLine (p3. Equals (p4));  True     Console.readkey ();}

If the above conclusion is correct, "= =" is a comparison of two variable values equal, then the following code should not be true.

Console.WriteLine (A = = B);         True

Obviously, the above two string variables: A/b is pointing to two different objects, that is, the memory addresses they store in the stack space are also different. But they're equal to the hairs?

2. What is operator overloading?

Operator overloading, which is to redefine an existing operator and give it another function to accommodate different data types. Make a simple analogy: the "+" operator, in the "+" two

When Benquan is a variable of a numeric type, the "+" operator represents a mathematical "+" meaning. If there is only one string type on either side of the "+" operator, then the "+" operator represents the connection

The meaning of the string. There are many instances of such operator overloading, so this is related to the topic of this article? I want to say that the above string variable: A, B is because of the string class

Overloaded with the operator "= =", see the following source code:

public static BOOL operator = = (String A, string b) {    return string.equals (A, b);} public static bool operator! = (Stri Ng A, String b) {    return! String.Equals (A, b);}

It is obvious that the "= =" operator is really overloaded in the string class, and that there is more than "= =" and "! =". and call the Equals method in the string class directly inside the overloaded operator method,

The source code is as follows:

public static bool Equals (string A, string b) {         if (object) a== (object) b)         {             return true;         }         if (Object) a==null | | (Object) b==null)         {             return false;         }         if (a.length! = b.length)             return false;         Return Equalshelper (A, b); }

From the top: the "= =" operator does not necessarily compare the values stored in two variables for equality, it depends on whether the current operator is currently overloaded in this type.

Rewrite of 3.Equals

Or the above example:

String a = new string (new char[] {' h ', ' e ', ' l ', ' l ', ' o '}); string b = new string (new char[] {' h ', ' e ', ' l ', ' l ', ' O '} ); Console.WriteLine (A = = B);         Trueconsole.writeline (A.equals (b));    True

From the above: A, B is a two different objects. But Equals is true, the above: "Equals is the comparison of whether two variables point to the same object" the conclusion is not tenable. Reason

Look at the Equals method in the String class:

public override bool Equals (Object obj) <br> {if (this = = null)  This was necessary to guard against Reverse-pinvokes and throw new NullReferenceException ();    Other callers who does not use the callvirt instruction string str = obj As String;    if (str = = null) return false;    if (Object.referenceequals (this, obj)) return true; if (this. Length! = str.    Length) return false; Return Equalshelper (this, str);} public bool Equals (String value) <br> {if (this = null)//this is necessary to Gua  Rd against Reverse-pinvokes and throw new NullReferenceException ();    Other callers who does not use the callvirt instruction if (value = = null) return false;    if (Object.referenceequals (this, value)) return true; if (this. Length! = value.    Length) return false; Return Equalshelper (this, value);} 

It is known from the above that the string class not only overrides equals in object but also has its own Equals method, but the implementation code is almost the same. Comparison type, memory address,

The actual value, thus obtaining the final result. So equals is not necessarily the same as a single comparison reference address, let alone we can also rewrite and customize. But rewrite

equals also has to be aware that if you need to use hashmap,hashset,hashtable then you also need to rewrite GetHashCode ().

4. Why is there a "= =" and equals?

China has a sentence: "The existence of any thing must have his existence of truth and value", the same way "= =" and equals is the same. The most basic implementation of "= =" in reference types is to

The memory addresses of the two objects are the same, and the same is equal and the other is unequal. This implementation is obviously from a hardware perspective, if the two objects are equal to the same object,

Then their addresses in memory are necessarily equal. But many times "behavior" depends on how we look at the world. such as: String type we declare a character

Strings are more concerned with the actual value of the string, rather than whether the two objects are created once or two times in memory (that is, if the memory addresses are equal), as long as they have

The actual values are equal then we think they are equal, which is understood from the business logic of life, not from the machine perspective. Of course the same string is declared above

Whether the variable is created once or twice I think: "Chang (or string detention pool)" has given us the best solution.

5. What is the relationship between "= =" and equals?

the "= =" operator and equals are actually complementary relationships. because: the main implementation of the "= =" operator is to stand in the "computer angle (or hardware angle)" to achieve,

While equals is a common business scenario or a specific business scenario to be implemented, there is no necessary connection between the two, according to their own business needs to choose different methods.

So equals in object is visual, and many classes rewrite it, and really achieve the specific behavior that is required in the current type: polymorphic. So it is not difficult to explain the above:

Object g = a;object h = b; Console.WriteLine (g = = h);         Falseconsole.writeline (G.equals (h));    True

Because the overloaded operator is not implemented in object: "= =", the current "= =" Comparison method is to compare whether the memory addresses stored in the stack space are the same for the two variables. and Equals is

Call equals in the String class, because the G variable is actually pointing to a string object while it is running, and the current object type is just the behavior of Visual Studio and the compiler, namely: or polymorphic.

Finally everything has its rules: "= =" and equals are no exception, please click on the details: Skip to MSDN.

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.