Home > Backend Development > C++ > C# String Comparison: When Does == Differ From Equals()?

C# String Comparison: When Does == Differ From Equals()?

DDD
Release: 2025-02-01 18:56:08
Original
257 people have browsed it

C# String Comparison: When Does == Differ From Equals()?

The difference between understanding C# == and equals ()

In C#, you may encounter this situation: Use == The comparative comparison of the component to compare the two string back to false, and the equals () method returns true. To understand this behavior, you must master the fundamental differences of these operators.

When used for objects, the value of == The value of the operator is System.object.referenceequals. This means that it checks whether the two string objects reference the same object in memory. Instead, Equals () is a virtual method that can be rewritten by custom types (including string).

For the string, use the rewriting version of Equals () to check the actual content of the string. Therefore, if you compare two string with the same character but stored in different memory positions, == will return to false because they are not referenced in the same object, and Equals () will return to TRUE because they are equal.

Code example:

Consider the following code fragment:

In this code, these two conditions will compare the Content properties of the selected listboxitem with the string "Energy Attack". Although the first condition of EQUALS () is calculated as true, if the Content property is a new string object, the second condition of == may be calculated as false. This is because the == operator check identification, and two different string objects with the same value are different.

<code class="language-c#">if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack"))
{
    // 执行代码
}

if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack")
{
    // 执行代码
}</code>
Copy after login
Therefore, when comparing the equal nature of the string in C#, it is recommended to use the Equals () method (it evaluates the equal nature of the content) instead of == (it check the logo).

The above is the detailed content of C# String Comparison: When Does == Differ From Equals()?. For more information, please follow other related articles on the PHP Chinese website!

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