Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 291
Yuriy Mayorov Avatar asked Jun 27 '13 19:06

Yuriy Mayorov


2 Answers

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.

like image 77
Mike Zboray Avatar answered Oct 16 '22 13:10

Mike Zboray


There are two important things going on here:

First, The expression "string" + 1 is evaluated at run-time while "string" + "1" is evaluated at compile-time.

Secondly, you're using reference comparison. The run-time generated strings actually reference different object while the compile-time generated strings reference the same object, so the first expression is false and the second expression is true.

If you're interested, the generated IL is:

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

IL_0000:  ldstr       "string"
IL_0005:  ldc.i4.1    
IL_0006:  box         System.Int32
IL_000B:  call        System.String.Concat
IL_0010:  ldstr       "string"
IL_0015:  ldc.i4.1    
IL_0016:  box         System.Int32
IL_001B:  call        System.String.Concat
IL_0020:  ceq         
IL_0022:  stloc.0     // a1
IL_0023:  ldstr       "string1"
IL_0028:  ldstr       "string1"
IL_002D:  ceq         
IL_002F:  stloc.1     // a2
like image 45
p.s.w.g Avatar answered Oct 16 '22 13:10

p.s.w.g