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
StringBuilder and String behaves differently with == operator. Thanks.
Two different reasons;
"Hello" string(s) are compiled into the source, they are the same reference - check ReferenceEquals(s1,s2) - it will return true
== / != (aka op_Equality / op_Inequality)The StringBuilder version fails because:
StringBuilder doesn't have the operatorsCall ToString() on each, and it gets more interesting:
true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With