0

Would someone please explain to me why boxing strings results in false return values? I don't understand ...

string a = string.Format("{0}{1}", "abc", "123");
string b = "abc123";
string c = "abc123";
Console.WriteLine(a == b);
Console.WriteLine((object)a == (object)b);
Console.WriteLine(c == b);
Console.WriteLine((object)c == (object)b);
CubeJockey
  • 2,209
  • 8
  • 24
  • 31
semper fi
  • 727
  • 3
  • 17
  • 32
  • 2
    Strings are reference types, and cannot be boxed. Your problem is that `==` binds to _compile-time_ types. – SLaks Jun 14 '16 at 16:18
  • 2
    Also, the strings referenced by `b` and `c` are interned, so they will _probably_ be the same reference, which will be different from `a`. Bottom line, use `Equals` for value equality instead of `==` – D Stanley Jun 14 '16 at 16:19
  • 2
    @DStanley: No; bottom line, don't cast to `object`. – SLaks Jun 14 '16 at 16:24
  • @SLaks but `Equals` will use value semantics even if you _do_ cast to `object`. – D Stanley Jun 14 '16 at 16:28
  • 2
    I think, you should look at [another SO answer](http://stackoverflow.com/a/3869613/364429). It must be very helpful for you I guess. – isxaker Jun 14 '16 at 16:30

0 Answers0