Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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++ :)

like image 714
Oleg Vazhnev Avatar asked Feb 13 '26 06:02

Oleg Vazhnev


1 Answers

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.

like image 81
Jon Skeet Avatar answered Feb 14 '26 19:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!