Why String behaves like a value type when using ==

want to know why String behaves like a value type when using ==.

String s1 = "Hello"; String s2 = "Hello"; Console.WriteLine(s1 == s2);// True(why? s1 and s2 are different) Console.WriteLine(s1.Equals(s2));//True StringBuilder a1 = new StringBuilder("Hi"); StringBuilder a2 = new StringBuilder("Hi"); Console.WriteLine(a1 == a2);//false Console.WriteLine(a1.Equals(a2));//true 

StringBuilder and String behave differently with the == operator. Thanks.

+6
c #
source share
5 answers

Two different reasons;

  • interning - since the string "Hello" compiled into the source, they are the same link - check ReferenceEquals(s1,s2) - it will return true
  • user equality - the string has equality operators (in particular, == / != (aka op_Equality / op_Inequality )

StringBuilder version StringBuilder because:

  • they are not the same link (these are regular managed objects created separately in the managed heap)
  • StringBuilder has no operators

A call to ToString() for everyone, and it becomes more interesting:

  • two lines are not the same link
  • but operator support guarantees true
+18
source share

The == operator is overloaded in the String class in such a way as to match string values ​​instead of references to objects that are standard.

+8
source share

Because the operator == is overridden for strings.

See MSDN

+3
source share

This is because the equality operator has been redefined to provide the functionality you see. You can do this on any type by overriding the equals operator.

0
source share

Using == for strings is bad practice, just use Equals ().

Details

-2
source share

All Articles