In an effort to explore how the C# compiler optimizes code, I've created a simple test application. With each test change, I've compiled the application and then opened the binary in ILSpy.
I just noticed something that, to me, is weird. Obviously this is intentional, however, I can't think of a good reason why the compiler would do this.
Consider the following code:
static void Main(string[] args)
{
int test_1 = 1;
int test_2 = 0;
int test_3 = 0;
if (test_1 == 1) Console.Write(1);
else if (test_2 == 1) Console.Write(1);
else if (test_3 == 1) Console.Write(2);
else Console.Write("x");
}
Pointless code, but I had written this to see how ILSpy would interpret the if
statements.
However, when I compiled/decompiled this code, I did notice something that had me scratching my head. My first variable test_1
was optimized to test_
! Is there a good reason why the C# compiler would do this?
For full inspection this is the output of Main()
that I'm seeing in ILSpy.
private static void Main(string[] args)
{
int test_ = 1; //Where did the "1" go at the end of the variable name???
int test_2 = 0;
int test_3 = 0;
if (test_ == 1)
{
Console.Write(1);
}
else
{
if (test_2 == 1)
{
Console.Write(1);
}
else
{
if (test_3 == 1)
{
Console.Write(2);
}
else
{
Console.Write("x");
}
}
}
}
UPDATE
Apparently after inspecting the IL, this is an issue with ILSpy, not the C# compiler. Eugene Podskal has given a good answer to my initial comments and observations. However, I am interested in knowing if this is rather a bug within ILSpy or if this is intentional functionality.
.locals init
routine. Each variable is, in fact, declared and is added to an array of objects. Subsequent objects are referenced by their position within that index, not their name. – PennadotPeek
showsnum1
,num2
num3
for variable names – Baer