开发者

How does the == operator work by default for strings? [duplicate]

This question already has an answer here: Closed 11 years ago.

Possible Duplicate:

Please tell why two references are same for string object in case of string( Code written below)

When I write in C# s1 == s2 where both declared as string would compiler compare references or content? I.e. if the == is overriden for string class?

I just wonder why this code prints "true":

string s1 = "hello"
string s2 = s1 + " ";
s2 = s2.Trim(); // i 开发者_开发技巧expect new object here
Console.WriteLine(s2 == s1);

Also I've some third-party sources where == is often used for strings comparision. This makes me crazy because I almost never use == to compare strings in Java and now I can't understand how this code works.

Is it normal to use == to compare strings in C#?

upd: Thanks to all, almost all answers are correct. To conclude:

  • Yes, it's normal to use "==" to compare string in C#
  • strings will be compared by content (not reference)
  • == operator for strings is NOT virtual.
  • strings in C# are immutable (this is similar to Java)

This behavior is different to Java where "==" for String class compares references.

see also Why strings does not compare references?

In my personal opinion language should not allow override or overload == operator, cause it makes it as difficult as c++ :)


Operators can't be overridden polymorphically, but they can be overloaded which is the case for string. The overload checks for content equality (in an ordinal fashion, with no culture sensitivity). So, for example:

string s1 = "hello";
string s2 = (s1 + " ").Trim();

object o1 = s1;
object o2 = s2;

Console.WriteLine(s1 == s2); // True - calls overloaded ==(string, string)
Console.WriteLine(o1 == o2); // False - compares by reference

Note how this is operating on exactly the same objects, but because overload resolution is performed at compile-time, in the second case the compiler doesn't know to call the string-specific operator.


yes, by default when you use == it checks for reference equiality, but it is overriden for strings so that it checks for content (because strings are immutable as well)

This is great article that I like (and author Jon is here as well :) )


Even though the System.String class is a reference type (which 'string' is an alias to) the == operation method on the type is overriden to provide comparison between the contents of the string types.

They are equal in your example because the contents of the string types are the same.


s2 == s1 will give you a boolean result, yes. As for .NET programming, I've always found it better to use String.Compare.


Yes, it's normal (but not necessarily good practice) to compare strings in C# with ==. String.Compare is a more reliable way of comparing, which can also take care of different character sets and case sensitivity.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜