7

Possible Duplicate:
C#: String.Equals vs. ==

Hi to all.

Some time someone told me that you should never compare strings with == and that you should use string.equals(), but it refers to java.

¿What is the diference beteen == and string.equals in .NET c#?

Community
  • 1
  • 1
Daniel Gomez Rico
  • 15,026
  • 20
  • 92
  • 162

8 Answers8

19

string == string is entirely the same as String.Equals. This is the exact code (from Reflector):

public static bool operator ==(string a, string b)
{
    return Equals(a, b); // Is String.Equals as this method is inside String
}
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
  • 1
    So, can I say that == is less performance than equals? – Daniel Gomez Rico Apr 26 '11 at 20:47
  • 3
    @Daniel G. R. No, small methods will be inlined by the just-in-time compiler so don't worry about that :) And if there is a VERY small time increase in the JIT-compiling itself, you shouldn't worry about that ;) – Lasse Espeholt Apr 26 '11 at 20:50
3

In C# there is no difference as the operator == and != have been overloaded in string type to call equals(). See this MSDN page.

Bala R
  • 107,317
  • 23
  • 199
  • 210
3

== actually ends up executing String.Equals on Strings.

You can specify a StringComparision when you use String.Equals....

Example:

MyString.Equals("TestString", StringComparison.InvariantCultureIgnoreCase)

Mostly, I consider it a coding preference. Use whichever you prefer.

Rob P.
  • 14,921
  • 14
  • 73
  • 109
1

The == operator calls the String.Equals method. So at best you're saving a method call. Decompiled code:

public static bool operator ==(string a, string b)
{
  return string.Equals(a, b);
}
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
1

Look here for a better description. As one answer stated

When == is used on an object type, it'll resolve to System.Object.ReferenceEquals.

Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).

Community
  • 1
  • 1
Soatl
  • 10,224
  • 28
  • 95
  • 153
0

no difference, it's just an operator overload. for strings it's internally the same thing. however, you don't want to get in a habit of using == for comparing objects and that's why it's not recommended to use it for strings as well.

Alex
  • 2,342
  • 1
  • 18
  • 30
0

In C# there's no difference for strings.

Andrei
  • 4,237
  • 3
  • 25
  • 31
0

If you dont care about the string's case and dont worry about cultural awarenes then it's the same...

Ivan Crojach Karačić
  • 1,911
  • 2
  • 24
  • 44