Home > Software design >  When does a variable get its value assigned in c#?
When does a variable get its value assigned in c#?

Time:07-26

Example:

string input=Console.ReadLine();
Base obj1;
if (input=="a"){
    obj1=Derived();
else{
    obj1=Base();
    }

In this case i know that a variable gets its value at runtime. But what happens when I just have int x=5;, when does x get its value, at runtime or compiletime?

CodePudding user response:

You can (almost) always check with IL/JIT ASM.

For a simple class, for example:

public class C {
    public void M() {
        var x = 6;
    }
}

Both IL and JIT ASM are for Debug configuration, in release unused variables will be cutted away.

IL:

.method public hidebysig 
        instance void M () cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 4 (0x4)
        .maxstack 1
        .locals init (
            [0] int32 x
        )

        IL_0000: nop
        IL_0001: ldc.i4.6 // Push 6 onto the stack as int32 (0x1C)
        IL_0002: stloc.0 // Pop a value from stack into local variable 0 (0x0A)
        IL_0003: ret
    } // end of method C::M

JIT ASM:

C.M()
    L0000: push ebp
    L0001: mov ebp, esp
    L0003: sub esp, 8
    L0006: xor eax, eax
    L0008: mov [ebp-8], eax
    L000b: mov [ebp-4], ecx
    L000e: cmp dword ptr [0x18d0c190], 0
    L0015: je short L001c
    L0017: call 0x6b214e50
    L001c: nop
    L001d: mov dword ptr [ebp-8], 6
    L0024: nop
    L0025: mov esp, ebp
    L0027: pop ebp
    L0028: ret

So as you can see, value 6, for example, is compiled into IL code itself as is, but assignment to [x], which is in memory, happens in the runtime.

Site to play around: https://sharplab.io/#v2:C4LghgzgtgNAJiA1AHwAICYCMBYAUKgZgAIMiBhIgbzyNpONQBYiBZACgEoqa7eA3MACciADyIBeIgDYA3D1oBfPAqA=

  • Related