15

Possible Duplicate:
C#: Are string.Equals() and == operator really same?

For string comparison, which approach is better (and safe):

string s1="Sarfaraz";
string s2="Nawaz";

bool result1 = (s1==s2) ;//approach 1
bool result2 = s1.Equals(s2) ;//approach 2

Or both are same under the hood?

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 1
    It depends if you consider "dog" and "Dog" to be the same word, while you can manipulate the string in your first approach using String.Equals(S1,S2,StringComparison.CurrentCultureIgnoreCase) can be handy and elegant. – Security Hound Jan 19 '11 at 20:13
  • one warning is that if the strings are null you will throw an exception. Of course they if you are comparing their value then your expecting a value. – Security Hound Jan 19 '11 at 20:32

1 Answers1

14

I like Equals() because the available StringComparison option is very useful.

The == and != operators are based on the value, so they are safe to use, even though String is a reference type.

DavidRR
  • 18,291
  • 25
  • 109
  • 191
CaptainPlanet
  • 735
  • 4
  • 8