✅ Does it matters which operator we use to compare strings, == or string.Equals?
Hello guys, I was just trying to compare 2 strings and my IDE give me this warning of using
string.Equals
. I was wondering if it does matter whether we use ==
or string.Equals
. From what I've read, it doesn't matter if the type is of type string but if it's of another type, like object or generic type (I guess), it does matter. Can someone explain why it would matter please; does this have something to do with comparing references rather than actual values?
10 Replies
specifically for case-insensitive comparison, prefer
string.Equals
there are some interesting gotchas with cases for some languages
the classic example is the turkish i
which can't be roundtripped iircoh ok, using string.Equals is more appropriate to perform culture-insensitive comparison ?
yes
there is also the StringComparison, does it differs from String.Equals ?
you mean
string.Compare
?hmm like what my IDE is suggesting StringComparison.Ordinal...
right so thats an enum that changes HOW the equality is evaluated
strings are complicated
see: UTF8, UTF16, ASCII...

so you have the culture-sensitive ones, then invariant ones, and finally ordinal
check these examples for how it works
https://learn.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=net-9.0#examples
yep, will have a look, thanks !