C# Confuses in string comparison: Are the String.Equals()
method and the ==
operator interchangeable?
In C#, string comparisons sometimes produce unexpected results. A common question is whether the String.Equals()
method and the ==
equal sign operator behave exactly the same.
Consider the following code snippet:
string s = "Category";
TreeViewItem tvi = new TreeViewItem();
tvi.Header = "Category";
Console.WriteLine(s == tvi.Header); // false
Console.WriteLine(s.Equals(tvi.Header)); // true
Console.WriteLine(s == tvi.Header.ToString()); // true
Although both s
s and
tvi.Headertvi.Header
]tvi, the ==
operator returns false
, while the String.Equals()
method returns
. This raises the question: Why do these two comparison methods produce different results?
Key Differences between String.Equals()
and ==
String.Equals()
and ==
operators:
==
operator is compared based on the compile-time type of the object, while String.Equals()
is polymorphic, meaning its implementation depends on the runtime type of the object being compared. ==
operator will not throw an exception when comparing null references, while String.Equals()
If any parameter is empty, a NullReferenceException
exception will be thrown. Example of demonstrating differences
]To illustrate these differences, consider the following code:
object x = new StringBuilder("hello").ToString();
object y = new StringBuilder("hello").ToString();
if (x.Equals(y)) // True
if (x == y) // False
Although the x
and y
y]y
] operator returns false
because it is compared based on the compile-time type of the object (object
) which are different. In order to get the correct comparison, the object must be explicitly converted to the appropriate type (in this case string
).
string xs = (string)x;
string ys = (string)y;
if (xs == ys) // True
in conclusion
While the String.Equals()
and ==
operators are usually used interchangeably, it is important to understand their nuances in implementation and null value processing. To ensure reliable and consistent string comparisons, the String.Equals()
method is generally recommended, especially when comparing different types of objects or handling empty references.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3