tags:

views:

1364

answers:

5

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?

+5  A: 

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."

Jorge Israel Peña
+12  A: 

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).

Matthew Scharley
There are slight differences.
Yuriy Faktorovich
Not as far as the values returned goes. `.Equals` does offer more options but `str1.Equals(str2)` is the same as `str1 == str2` as far as what you get as a result. I do believe they use different methods for determining the equality as Jon Skeets quote that Blaenk brings up would indicate, but they give the same values.
Matthew Scharley
Functionality wise they are the same, but computationally there are slight differences.
Yuriy Faktorovich
@Yuriy Perhaps you could elaborate or provide a link on the differences?
Kirk Broadhurst
From Blaenk's answer: http://dotnetperls.com/string-equals-compare
Matthew Scharley
Basically, it boils down to one less null check (since you don't have to check whether `this` is null or not)
Matthew Scharley
Isn't string.Equals considered a MSFT best practice (via FxCop?)
Robaticus
+6  A: 

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.

Michael Petrotta
+3  A: 

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));
}
Ed Courtenay
A: 

Moved it to http://stackoverflow.com/questions/3678792/c-are-string-equals-and-operator-really-same

miliu
If you're really interested in some answers to your question you should make up a new question, put your text there, add a reference to this question and delete your *answer* here.
Oliver
@miliu you should post this as a brand new question and provide a link back to this question. This way, people can provide a new answer specific to your situation. Otherwise, people are stuck leaving "answers" in the comments, which doesn't benefit from the whole StackOverflow.com QA engine. Best of luck!
Ben McCormack