C
C#2mo ago
Faker

✅ 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?
No description
10 Replies
Pobiega
Pobiega2mo ago
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 iirc
Faker
FakerOP2mo ago
oh ok, using string.Equals is more appropriate to perform culture-insensitive comparison ?
Pobiega
Pobiega2mo ago
yes
Faker
FakerOP2mo ago
there is also the StringComparison, does it differs from String.Equals ?
Pobiega
Pobiega2mo ago
you mean string.Compare?
Faker
FakerOP2mo ago
hmm like what my IDE is suggesting StringComparison.Ordinal...
Pobiega
Pobiega2mo ago
right so thats an enum that changes HOW the equality is evaluated strings are complicated see: UTF8, UTF16, ASCII...
Pobiega
Pobiega2mo ago
No description
Pobiega
Pobiega2mo ago
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
Faker
FakerOP2mo ago
yep, will have a look, thanks !

Did you find this page helpful?