Home > Backend Development > C++ > C# String Comparison: When Should I Use `==` vs. `Equals()`?

C# String Comparison: When Should I Use `==` vs. `Equals()`?

Mary-Kate Olsen
Release: 2025-02-01 19:16:13
Original
664 people have browsed it

C# String Comparison: When Should I Use `==` vs. `Equals()`?

C# character string equal sexual problems:

and compare == Equals() C# offers two comparison string operators:

and

. Although they seem to be able to swap, they show unique behaviors and may lead to unexpected results. Let's explore this language problem through a specific scene. == Equals() In a Silverlight application, one condition compares two string:

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

if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack")
{
    // 执行代码
}</code>
Copy after login
Compare False, and

call back true. Why is there such a difference? == Equals() The answer lies in the underlying implementation of these operators. When used with an object expression,

will be evaluated as

. This method compares the object reference, not the == content System.Object.ReferenceEquals. In this case, the two string are stored in different memory positions, so return to false. ReferenceEquals On the other hand, is a virtual method that can be rewritten by derived type. For string types, the rewrite version of the actual

content

, thereby returning True. Equals Therefore, for comparison of the string of string, it is recommended to use , it is more intuitive, and it performs the content -based comparison.

The above is the detailed content of C# String Comparison: When Should I Use `==` vs. `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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template