开发者

Why String behaves like value type while using ==

开发者 https://www.devze.com 2022-12-10 17:56 出处:网络
want to know why Stringbehaves like value type while using ==. String s1 = \"Hello\"; String s2 = \"Hello\";

want to know why String behaves like value type while 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

StringBuilde开发者_StackOverflowr and String behaves differently with == operator. Thanks.


Two different reasons;

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

The StringBuilder version fails because:

  • they aren't the same reference (these are regular managed objects created separately on the managed heap)
  • StringBuilder doesn't have the operators

Call ToString() on each, and it gets more interesting:

  • the two strings aren't the same reference
  • but the operator support guarantees a true


The == operator is overloaded in the String class, in a way that makes the string values to be compared instead of the object references, which is the default.


Because == operator is redefined for strings.

See MSDN


It's because the equality operator has been overridden to provide the functionality you see. You can do this on any type by overriding the equals operator.


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

Details

0

精彩评论

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