Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why String behaves like value type while using ==

Tags:

c#

.net

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.

like image 825
Wondering Avatar asked Nov 09 '09 12:11

Wondering


1 Answers

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
like image 127
Marc Gravell Avatar answered Oct 18 '22 17:10

Marc Gravell