Home > Backend Development > C#.Net Tutorial > A brief analysis of the sample code of '==' and Equals in C#

A brief analysis of the sample code of '==' and Equals in C#

黄舟
Release: 2017-03-09 15:43:55
Original
1160 people have browsed it

Most netizens summarized "==" and Equals like this:

  1. "==" compares the values ​​of two variables for equality.

  2. Equals compares whether two variables point to the same object.

For example: this article, and take the examples in 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();
 }
Copy after login

If the above conclusion is correct and "==" compares the values ​​of two variables to be equal, then the following code should not be True.

Console.WriteLine(a == b);         //true
Copy after login

Obviously, the two string variables above: a and b point to two different objects, that is, the memory addresses they store in the stack space are also different. But why are they equal?

2. What is operator overloading?

Operator overloading is to redefine an existing operator and give it another function to adapt to different data types. Let’s make a simple analogy: “+” operator, in “+” two

When all edges are variables of numerical type, the "+" operator represents the mathematical meaning of "+". If either side of the "+" operator is of string type, then the "+" operator represents a connection

The meaning of the string. There are many examples of such operator overloading, so does this have anything to do with the topic of this article? What I want to say is that the above string variables: a, b are because of the String class

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

public static bool operator == (String a, String b)
{
    return String.Equals(a, b);
}
 public static bool operator != (String a, String b)
{
    return !String.Equals(a, b);
}
Copy after login

It is obvious that the "==" operator is really overloaded in the String class, and not only "==" but also "!=". And directly call the Equals method in the String class 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);
 }
Copy after login

From the above: The "==" operator does not necessarily compare whether the values ​​stored in two variables are equal. This depends on whether the current operator is overloaded in the current type.

3. Rewriting of Equals

Still 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);         //true
Console.WriteLine(a.Equals(b));    //true
Copy after login

It can be seen from the above that: a and b are two different objects. But if Equals is True, the above conclusion: "Equals compares whether two variables point to the same object" is not valid. reason

Look at the Equals method in the String class:

public override bool Equals(Object obj) <br>       {
    if (this == null)                        //this is necessary to guard against reverse-pinvokes and
        throw new NullReferenceException();  //other callers who do 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 guard against reverse-pinvokes and
        throw new NullReferenceException();  //other callers who do 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);
}
Copy after login

As can be seen from the above, the String class not only rewrites the Equals in Object but also has its own Equals method, but the implementation code is almost the same. Comparison type, memory address,

Actual value to obtain the final result. So Equals is not necessarily a single comparison of whether the reference addresses are the same, not to mention that we can also rewrite and customize it. But rewrite

Equals also needs attention, that is, if you need to use HashMap, HashSet, Hashtable, then you also need to rewrite GetHashCode().

4. Why do we need Equals when we have "=="?

There is a Chinese saying: "The existence of anything must have its own reason and value." The same goes for "==" and Equals. The most basic implementation of "==" in reference types is to compare

Compare whether the memory addresses of the two objects are consistent. If they are consistent, they are equal, otherwise they are not equal. Such an implementation is obviously thought from a hardware perspective. If two objects are equal, they are the same object.

Then their addresses in memory must be equal. But many times "behavior (method)" depends on the perspective from which we observe the world. For example: String type, we declare a character

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

If the actual values ​​are equal, then we consider them to be equal. This is understood from the business logic of life rather than from a machine perspective. Of course the same string declared above

Whether variables are created once or twice I think: "Constant pool (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. Because: The main implementation form of the "==" operator is implemented from the "computer perspective (or hardware perspective)",

Equals is implemented based on common business scenarios or specific business scenarios. There is no inevitable connection between the two. You just choose different methods according to your own business needs.

So Equals in Object is Visual. It has been rewritten in many classes and truly achieves the specific behavior required in the current type, that is: polymorphism. So it is not difficult to explain the above:

object g = a;
object h = b;
Console.WriteLine(g == h);         //false
Console.WriteLine(g.Equals(h));    //true
Copy after login

Because the overloaded operator "==" is not implemented in Object, the current comparison method of "==" is to compare whether the memory addresses stored in the stack space of the two variables are the same. And Equals is

Call Equals in the String class because the g variable actually points to a string object during operation, and the current Object type is just the behavior of Visual studio and the compiler, that is: it is still polymorphic.

In the end, everything has its rules: "==" and Equals are no exception. For details, please click: Jump to MSDN.


The above is the detailed content of A brief analysis of the sample code of '==' and Equals in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template