I'm using Visual Studio's Watch panel to investigate variables as I run my program. In the following code, both test1
and test2
variables are added to the Watch panel. As expected, they both evaluate to true
.
object a = "123";
object b = "123";
bool test1 = a == b;
bool test2 = (object)"123" == (object)"123";
However, as seen by the third line, if I manually add the expression for the test2
variable, it evaluates to false
.
Why the same line yields different result in the Watch window? Is it some kind of optimization in work here? Under what circumstances can the same string be allocated to different addresses?
There are a few things going on here, the first is that when you use string literals in your C# code, these have to be included in the compiled assembly, so to avoid bloating the assembly, the compiler only outputs each unique string once, and they are automatically "interned" at runtime (see: https://learn.microsoft.com/en-us/dotnet/api/system.string.intern). All uses of a given string literal will therefore be the same string instance.
As a result of the above, all uses of "123"
in your code are the same string instance at runtime, which is why both test1
and test2
are true
, since your ==
is performing reference equality, and both sides are the same exact string instance in both cases.
However, when you use the watch window, the debugger creates new string instances for each of the string literals in your expression, so they are not the same instance, and so comparing them with object
’s ==
returns false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With