C# – What happens behind the scenes when you set an Int32 equal to an Int16

cnetruntime

What goes on at a low level when I do this?

Int32 a = 0;
Int16 b = 50;

a = b;

Best Answer

Something like this:

IL_0001:  /* 1F   | 32               */ ldc.i4.s   50
IL_0003:  /* 0B   |                  */ stloc.1
IL_0004:  /* 07   |                  */ ldloc.1
IL_0005:  /* 0A   |                  */ stloc.0

At a lower level, it depends on the machine architecture and optimization level. Code like this specifically, that has no effect, will probably just be omitted altogether. Otherwise, it'll be simple code, perhaps like this:

movsx eax, word ptr [ebp+12]
mov [ebp+8], eax

movsx is the x86 instruction which preserves the sign of a shorter number when it's being loaded into a larger destination; basically, it looks at the most significant bit of the smaller source and copies it into the remaining bits when it's extending the number.