[C #] = = VS Equals

Source: Internet
Author: User

Disclaimer: This blog post is translated from: Https://www.codeproject.com/Articles/1111680/equalsequals-VS-Equals-in-Csharp

Due to the level (technical level + English comprehension ability) Limited/insufficient, certainly will have the omission/the mistake, please correct in time.

Introduced:

In C #, you can use "= =" and an overloaded "Equals ()" method to compare variables. But many developers do not know the difference between the two. In this blog you will discuss the differences between the two and the use of both scenarios. There is no difference between "= =" and "Equals ()" except when making a string comparison.

Comparison rules: The comparison in C # is nothing more than a comparison of value types and reference types. When a value type is compared, the content of the value type is compared, and when the reference type is compared, the reference to the object is the same (memory address) instead of "content." The above rules apply to "= =" and "Equals ()".

Scenario One: Value type comparison

When you compare value types (int, double, byte etc), both "= =" and "Equals ()" Are comparison of content based on value types. The contents of the value type are the same, the two are equal.

Console.WriteLine ("Value Type Compare ... " ); int Ten ; int Ten  = = y);        // true // true
Scenario Two: Reference type comparison

When comparing reference types (object, interface), the comparison is whether the reference (memory address) is the same, and in the following code OBJ1 and OBJ2 are compared using "= =" and "Equals", with the result: false. Although the contents of two objects are the same. But the content address is not the same.

classcustomer{ Public stringName {Get;Set; }} Customer obj1=NewCustomer (); obj1. Name="Jimmy-yang"; Customer Obj2=NewCustomer (); obj2. Name="Jimmy-yang"; Console.WriteLine (Obj1= = Obj2);//falseConsole.WriteLine (obj1. Equals (OBJ2));//false

If Obj1 and Obj2 point to the same reference (memory address).

New"jimmy-yang"== = = = Obj2);        // true Console.WriteLine (obj1. Equals (OBJ2));   // true
Scenario Three: string comparison

The string type is a reference type, then "str" in the code below creates a string object and stores the "test" character on the heap memory block. When STR1 is created, it is stored in a different area of memory, although it stores the same content.

Object " Test " ; Object " Test "  = = str1);         // true Console.WriteLine (str. Equals (STR1));    // ture

Execution results found that STR is equal to STR1. What is this for?
Note: The string type of C # follows an internal rule. If STR is the same as STR1, both point to the memory address of the system. therefore, "= =" and "Equals" return true.

But note the following code, we create a separate object and assign it to a string type. At this point the "= =" Comparison will return False,equals () will return true. This is a different place between the two.

Objectstr =New string(New Char[] {'T','e','s','T' });ObjectSTR1 =New string(New Char[] {'T','e','s','T' }); Console.WriteLine (str= = str1);//falseConsole.WriteLine (str. Equals (STR1));//true
Scenario four: Compile-time vs runtime

The difference between the two when doing type checking. = = does type checking at compile time; Equals () does type checking at run time. Take a look at the code below and there will be a warning message in "= =".

Scenario Five: NULL

When the object being compared is null, "= =" does not throw an exception, and "Equals ()" is crash directly when comparing null objects.

Usage Scenarios

"= =" is an operator provided by C #, and "Equals ()" is a virtual method provided by the base class that can inherit from the subclass and write its own comparison logic. In other words, "= =" is a feature of C #, and Equals is a feature of OOP. The difference between the two is based on pure content and reference (memory address) comparisons. The other is based on the semantics (semantics, here I translate idiom meaning, actually more exactly should be the meaning between objects) on the comparison. For example: 1 <> 10 (technically speaking), but real life, 1 Yuan = 10 angle, at this time 1=10 in the meaning.

    • If the comparison is purely technical, please use "= =";
    • If you are semantically compared (for example: $1 = 10), you need to use the Equals method and provide the appropriate comparison logic.
Summarize

Take a look at the following table:

== Equals
Usage Technical based Semantic based
Value types Content based Comparison Content based Comparison
Objects Reference based Comparison Reference based Comparison
String Content based Comparison Content based Comparison
String with no interning Reference based Comparison Content based Comparison
Type Checking Compile time Run time
Nulls Works Can crash

[C #] = = VS Equals

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.