Search code examples
c#.netstringconcatenation

C# concatenation strings while compiling


Please help understand this behavior. When I use this:

bool a1 = (object)("string" + 1) == ("string" + 1);

The result is false

But when I use this

bool a2 = (object)("string" + "1") == ("string" + "1"); 

The result is true

So, why a1 != a2?


Solution

  • Casting to object forces a reference equality comparison.

    In the first case two different string objects are generated at runtime. Since they are different instances the result is false.

    In the second case the compiler notices that "string" + "1" is always going to be "string1" and interns the string and uses the same reference in both places. Since it is the same string reference, the result is true.