Pass 'value type' on the stack using ref-memory footprint

What happens in memory when we pass in the type of value - which was stored on the stack - by reference?

A temporary value / pointer must be created somewhere in order to change the original value when the method is completed. Can someone explain or show me the answer - a lot of material in my memory, but no one seems to be responding to this. tee

+3
source share
2 answers

If you have a way like this:

static void Increment(ref int value)
{
   value = value + 1;
}

and name it as follows:

int value = 5;
Increment(ref value);

, , 5 , value . value Increment, .

IL :

.method private hidebysig static void Increment(int32& 'value') cil managed
{
    .maxstack 8
    L_0000: nop 
    L_0001: ldarg.0 
    L_0002: ldarg.0 
    L_0003: ldind.i4         // loads the value at the location of 'value'
    L_0004: ldc.i4.1 
    L_0005: add 
    L_0006: stind.i4         // stores the result at the location of 'value'
    L_0007: ret 
}

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 9
    .locals init ([0] int32 value) //   <-- only one variable declared
    L_0000: nop 
    L_0001: ldc.i4.5
    L_0002: stloc.0 
    L_0003: ldloca.s 'value'   // call Increment with the location of 'value'
    L_0005: call void Program::Increment(int32&)
    L_000a: ret 
}
+4

, Unboxing, , .

, , - .

0

Source: https://habr.com/ru/post/1716022/


All Articles