Home Backend Development C#.Net Tutorial Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

Dec 16, 2016 am 09:45 AM

First look at the comparison between basic value types in the CLR, first look at the code:

            int age1 = 30;            int age2 = 30;

            Console.WriteLine("int == int: {0}", age1 == age2);
            Console.WriteLine("int == int: {0}", age2 == age1);
            Console.WriteLine("int Equals int: {0}", age1.Equals(age2));
            Console.WriteLine("int Equals int: {0}", age2.Equals(age1));
            Console.WriteLine("int ReferenceEquals int: {0}", object.ReferenceEquals(age1, age2));
            Console.WriteLine("int ReferenceEquals int: {0}", object.ReferenceEquals(age2, age1));

            Console.ReadLine();
Copy after login

Running results:

Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

For the same basic value type (both int in the above example code), == and Equals() The comparison results are the same; since ReferenceEquals() determines whether the references of two objects are equal, for value types, because a boxing operation must be performed before each judgment, that is, a temporary object is generated each time, so it will never Return false. Next, I change the type of age2 in the code to byte type. What will happen to the comparison results? Please look at the running results:

Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

Now we find that the results of age1.Equals(age2) and age2.Equals(age1) are different. In the comparison of basic value types, == compares the content of "value". If the "value" of two objects is the same, then the two objects are "=="; but Equals() does a little more. One point, there is actually an "implicit conversion" process in Equal(), which means that age1.Equals(age2) in the above code is equivalent to int.Equals(int), and byte data can be implicitly converted to Int type data, so the result of age1.Equals(age2) is true; and age2.Equals(age1) is equivalent to byte.Equals(byte), but int type data cannot be implicitly converted to byte type because there is a possibility of loss of data precision. . In fact, the Equals() of age2.Equals(age1) should be similar to the following code:

        public override bool Equals(object obj)
        {            if (!(obj is Byte))
            {                return false;
            }            return m_value == ((Byte)obj).m_value;
        }
Copy after login

If it is an explicit conversion, the result of age2.Equals((byte)age1) will be true at this time.

Let’s talk about the comparison between string types. String is a special reference type because it is "immutable". Let’s look at the code first:

            string name1 = "Jack";            string name2 = "Jack";            object o1 = name1;            object o2 = name2;

            Console.WriteLine("name1 == name2: {0}", name1 == name2);
            Console.WriteLine("name1 Equals name2: {0}", name1.Equals(name2));

            Console.WriteLine("o1 == o2: {0}", o1 == o2);
            Console.WriteLine("o1 Equals o2: {0}", o1.Equals(o2));

            Console.WriteLine("o1 == name2: {0}", o1 == name2);
            Console.WriteLine("o1 Equals name2: {0}", o1.Equals(name2));

            Console.WriteLine("name1 ReferenceEquals name2: {0}", object.ReferenceEquals(name1, name2));
            Console.WriteLine("o1 ReferenceEquals o2: {0}", object.ReferenceEquals(o1, o2));

            Console.ReadLine();
Copy after login

The results of the above code execution:

Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

The comparison results are all true, now we will explain them one by one. Some people will say that name1 and name2 both store "Jack", so name1 and name2 are actually the same object, so the comparison results of name1==name2 and name1.Equals(name2) are the same; maybe you are right. When we view the source code of string through the .NET Reflector tool, we will see this piece of code:

Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

operator == actually returns Equals(). So for the explanation of why the comparison results of name1==name2 and name1.Equals(name2) are the same, I think this explanation is more intuitive than "name1 and name2 are actually the same object".

We know that due to the particularity of the string type, the CLR can share multiple identical string contents through a string object, so the above name1 and name2 point to the same place, and the following o1 == o2, o1 == The comparison results of name2 and object.ReferenceEquals(name1, name2) are all true, which also verifies this statement (in fact, object.ReferenceEquals(name1, o2) is also true). However, what if the assignment of name1 and name2 becomes like this?

            string name1 = new string(new char[] { 'J', 'a', 'c', 'k' });
            string name2 = new string(new char[] { 'J', 'a', 'c', 'k' });
Copy after login

Look at the running results:

Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

The comparison results of name1==name2 and name1.Equals(name2) are as easy to understand. As mentioned above, operator== actually returns Equals() (for For reference types, Equals() compares the contents stored on the managed heap), so the results are the same. But when comparing object objects o1 and o2, the results of o1 == o2 and o1.Equals(o2) are different. == of object objects compares type object pointers. o1 and o2 are two objects, and their type object pointers must be different; Equals() compares the contents of o1 and o2 stored on the managed heap, so o1.Equals (o2) is true. This also shows that the following o1 == name2 is false and o1.Equals(name2) is true.

Let’s take a look at the internal code of object.ReferenceEquals first:

Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

Now it should be easy to understand that the results of object.ReferenceEquals(name1, name2) and object.ReferenceEquals(o1, o2) are both false. In fact, they are two == problem of object!

Finally, let’s talk about the comparison of custom reference types.

    class MyName
    {
        private string _id;
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public MyName(string id)
        {
            this.Id = id;
        }
    }
Copy after login

Change the above declarations of name1 and name2 to:

            MyName name1 = new MyName("12");
            MyName name2 = new MyName("12");
Copy after login

Others remain unchanged, and the running result is:

Understand the differences between ==, Equals() and ReferenceEquals() in C# at once

name1 and name2 are two completely different objects. It should be easy to understand that the comparison results are all false.




For more related articles on understanding the differences between ==, Equals() and ReferenceEquals() in C# at once, please pay attention to 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Apr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Apr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

Is C# .NET Right for You? Evaluating its Applicability Is C# .NET Right for You? Evaluating its Applicability Apr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

Building Microservices with C# .NET: A Practical Guide for Architects Building Microservices with C# .NET: A Practical Guide for Architects Apr 06, 2025 am 12:08 AM

C#.NET is a popular choice for building microservices because of its strong ecosystem and rich support. 1) Create RESTfulAPI using ASP.NETCore to process order creation and query. 2) Use gRPC to achieve efficient communication between microservices, define and implement order services. 3) Simplify deployment and management through Docker containerized microservices.

See all articles