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
  • 13,991
  • 15
  • 88
  • 150

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,432
  • 5
  • 61
  • 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
  • 104,615
  • 23
  • 192
  • 207
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,588
  • 14
  • 71
  • 106
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
  • 64,850
  • 14
  • 101
  • 138
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
  • 9,924
  • 28
  • 91
  • 149
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,292
  • 1
  • 17
  • 29
0

In C# there's no difference for strings.

Andrei
  • 4,187
  • 3
  • 24
  • 29
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,883
  • 2
  • 24
  • 44