C # string comparison?

Possible duplicates:
Using == or Equals to compare strings
Are the string.Equals () and == statements really the same?

I first studied Java, and one of the few absolutes is that you never use == to compare if the two lines are equal, instead there is an equals method. So when I landed in C # a few years ago and noticed that the objects still have the Equals method, I assumed that the rule still applies.

Now I look at the ex-coworker code, and everywhere I find the following snippets:

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

If I remember correctly, == will compare the address between the two results, and since the first half is returned by the function, this will not be done, because the result will not be the same address as the constant on the right.

Am I holding on to old Java habits? Or is it good that my colleague is no longer around?

PS Regardless of your answer to string comparison, I understand that the above would be better indicated as s.BeginsWith("GBCI"), but something else entirely.

+3
source share
2 answers

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

So using it, it works great; your colleague was sober and sober.

+8
source

As another note, check out this link.

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

0

All Articles