开发者

C# String Comparison? [duplicate]

This question already has answers here: Closed 11 years ago.

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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜