I recently was introduced to a large codebase and noticed all string comparisons are done using String.Equals() instead of ==.
What's the reason for this, do you think?
I recently was introduced to a large codebase and noticed all string comparisons are done using String.Equals() instead of ==.
What's the reason for this, do you think?
There's a writeup on this article which you might find to be interesting, with some quotes from Jon Skeet. It seems like the use is pretty much the same.
Jon Skeet states that the performance of instance Equals "is slightly better when the strings are short—as the strings increase in length, that difference becomes completely insignificant."
It's entirely likely that a large portion of the developer base comes from a Java background where using ==
to compare strings is wrong and doesn't work.
In C# there's no (practical) difference (for strings).
String.Equals
does offer overloads to handle casing and culture-aware comparison. If your code doesn't make use of these, the devs may just be used to Java, where (as Matthew says), you must use the .Equals method to do content comparisons.
I sometimes use the .Equals method, because it can make things slightly clearer and more concise at times. Consider:
public static bool IsHello(string test) {
return (test != null && test == "Hello");
}
The test for NULL can be completely ignored if using .Equals like so:
public static bool IsHello(string test) {
return ("Hello".Equals(test));
}