3

Possible Duplicates:
Using == or Equals for string comparison
Are string.Equals() and == operator really same?

I learned Java first and one of the few absolutes is that you never use == to compare if two strings are equal, instead there's the equals method. So when I landed in C# years ago and noticed that objects still had an Equals method, I assumed the rule still applied.

Now I'm going through an ex-coworker's code and I'm finding snippets like this everywhere:

if (s.Substring(0, s.IndexOf("_")) == "GBCI") {...}

If I recall correctly, == will compare the address between those two results and since the first half is returned by a function, this will fail because the result won't be the same address as the constant on the right.

Am I holding on to old Java habits? Or is it a good thing that my coworker isn't around any more?

P.S. Regardless your answer to comparing strings, I do realize the above would be better stated as s.BeginsWith("GBCI"), but that's something else entirely.

Community
  • 1
  • 1
Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
  • Regarding the PS. it would be if (s.BeginsWith("GBCI_") == true). And that is a lot better. – David May 17 '11 at 19:29
  • Or even `if (s.BeginsWith("GBCI_"))` – BoltClock May 17 '11 at 19:29
  • I prefer BoltClock's way. If it returns a bool, why compare that to a bool in order to get another bool? The line 'x == true' will return exactly the same thing as simply 'x' (saying that x is a bool of course) – Corey Ogburn May 17 '11 at 19:34
  • Oh, I see what you changed, mostly the _ involved in the constant string. I certainly see why you think that it should be there, but what you didn't know (and I don't chide you for it) is that the underscore doesn't matter. The string in question either begins with GBCI or CSB, just had to figure out which one. – Corey Ogburn May 17 '11 at 19:47

2 Answers2

8

In C#, == comparison for strings compares their values instead of their references. See this section of the C# spec for details.

So using it like that works fine; your coworker was sane and sober.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0

As another note, look at this link.

You can use == however compareTo is unique in that it will return an integer based on how the strings differ (or don't differ).

slandau
  • 23,528
  • 42
  • 122
  • 184