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#

Mar 09, 2017 pm 03:43 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles