0

I am a bit skeptical as to why the third scenario returning false. And, how exactly object reference works

//Case 1
    string a = "helloworld";
    string b = "helloworld";
    var result = object.ReferenceEquals(a, b); //Output is true

//Case 2    
    string a = "helloworld";
    string b = "hello" + "world";
    var result = object.ReferenceEquals(a, b); //Output is true

//Case 3    
    string a = "helloworld";
    string b = "hello";
    b = b + "world";
    var result1 = object.ReferenceEquals(a, b); //Output is false
Ajay
  • 643
  • 2
  • 10
  • 27
  • 4
    Basically, the compiler will perform concatenation on string constants to produce more constants, and all constants will resolve to the same object. In your third scenario, the concatenation is performed at *execution* time. It's really unclear what you mean by "And how exactly object reference works"... – Jon Skeet Sep 20 '16 at 09:48
  • For your amusement, here's another case: `const string c = "hello"; string b = c + "world";` – Kris Vandermotten Sep 20 '16 at 09:50
  • Your actual question seems to be _"Why doesn't the resulting string from concatenation using variables get interned the way it does when concatenating inline?"_ or something like that, but it's all explained in the [duplicate that explains string interning pretty thoroughly](http://stackoverflow.com/questions/8054471/string-interning-in-net-framework-what-are-the-benefits-and-when-to-use-inter). – CodeCaster Sep 20 '16 at 09:51
  • And another `StringBuilder b = new StringBuilder("hello"); b.Append("world");` and `var result = object.ReferenceEquals(a, b.ToString());` also returns `false` – Peter Smith Sep 20 '16 at 09:55
  • As for your edit, that's not what I meant, and try searching. See also [C# string concatenation and string interning](http://stackoverflow.com/questions/38010/c-sharp-string-concatenation-and-string-interning), [String interning?](http://stackoverflow.com/questions/2706607/string-interning), and so on. – CodeCaster Sep 20 '16 at 09:58
  • Will do that for sure.....I am confused right now – Ajay Sep 20 '16 at 09:58
  • Please read [ask] and [edit] your question to explain, very explicitly, what you expect to see and what exactly you are confused about. – CodeCaster Sep 20 '16 at 10:06

0 Answers0