开发者

'==' vs string.equals c# .net [duplicate]

This question already has answers here: Closed 11 years ago开发者_开发百科.

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#?


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
}


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


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


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


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);
}


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.


In C# there's no difference for strings.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜