3

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

I know that in c# you can compare string with == and equals but I want to know what is that I need to use according to best practices. Note that I need to know if it's the same for String and string

Community
  • 1
  • 1
Jorge
  • 17,896
  • 19
  • 80
  • 126
  • http://stackoverflow.com/questions/1659097/c-string-equals-vs and http://stackoverflow.com/questions/3678792/are-string-equals-and-operator-really-same – SwDevMan81 Jun 21 '11 at 23:26

7 Answers7

7

String and string are exactly the same in C#. The "best practice" would be identical.

Whether to use == or Equals, in the case of string, is somewhat personal preference. I personally prefer ==, as its a bit more readable (in my opinion) and far shorter to type.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

Most .Net developers seem to like using the keyword string instead of System.String or String.

If you are not ignoring case, then string1 == string2 is most appropriate because you don't have to check either value for null as you would here: string x = null;x.Equals("junk");.

If you want to ignore the case (so STRING is equal to string), use this:

string.Equals (string1, string2, StringComparison.CurrentCultureIgnoreCase)

(or one of the other values in StringComparison.)

agent-j
  • 27,335
  • 5
  • 52
  • 79
2

string is really System.String, the change is done for you by the compiler. == just calls String.Equals.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
0

String and string are the same thing internally.

Personally, I would use == for readability. There's no performance difference between == and .Equals; == calls .Equals behind the scenes.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
0

Since C# has operator overloading and ==, != are overloaded the responsibility should fall to the person person modifying your code should know to check if the operator == or != is overloaded before assuming that it is doing an Object comparison.

NOTE: If you wanted to do a reference comparison you can do the following:

if( (object)a == b )
Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
Suroot
  • 4,315
  • 1
  • 22
  • 28
0

They are identical. (Although Equals has some overrides, but I assume you are not talking about them).

For best practices, refer to your colleagues and use the one they do. It helps to be consistent in the same codebase.

If you work alone, pick the one you like more!

Andrei
  • 4,880
  • 23
  • 30
0

According to the Framework Guidelines (or Effective C# I forgot which one) it is better to use String when you want to use the class and string when you want to declare a string type:

string result = String.Format("You have {0} items.", items);

(Though I would use var result if its a local variable)

As for comparison, I would use String.Compare() so that you can use various comparisons like ignore case.

MackPro
  • 198
  • 4