How does the ref keyword work (in terms of memory)

后端 未结 4 2010
广开言路
广开言路 2021-02-12 13:48

C# has a ref keyword. Using ref you can pass an int to a method by reference. What goes on the stack frame when you call a method that accepts an int by reference?



        
4条回答
  •  借酒劲吻你
    2021-02-12 13:53

    Here is a simple example in C# code:

    void Main()
    {
        int i = 1;
        inc(ref i);
        Console.WriteLine(i);
    }
    
    public void inc(ref int i) { 
      i++;
    }
    

    Here is the generated IL code

    IL_0000:  nop         
    IL_0001:  ldc.i4.1    
    IL_0002:  stloc.0     // i
    IL_0003:  ldarg.0     
    IL_0004:  ldloca.s    00 // i
    IL_0006:  call        inc
    IL_000B:  nop         
    IL_000C:  ldloc.0     // i
    IL_000D:  call        System.Console.WriteLine
    IL_0012:  nop         
    IL_0013:  ret         
    
    inc:
    IL_0000:  nop         
    IL_0001:  ldarg.1     
    IL_0002:  dup         
    IL_0003:  ldind.i4    
    IL_0004:  ldc.i4.1    
    IL_0005:  add         
    IL_0006:  stind.i4    
    IL_0007:  ret     
    

    Note with this simple case there is really only one difference ldloca.s 00 or ldloc.0. Load local or load address (of offset 00)

    That is the difference at the simplest level (which is what you asked for in your comment) -- if you load the value of the variable or you load the address of the variable. Thing can get complicated quickly -- if the function you are calling is not local, if the variable you are passing is not local etc etc etc. But at a basic level this is the difference.

    I used linqpad to do my quick diss-assembly -- I recommend it. http://www.linqpad.net/

提交回复
热议问题