Do int ref parameter get boxed?

后端 未结 6 1921
-上瘾入骨i
-上瘾入骨i 2021-02-12 13:14

Say I have the following code:

void Main()
{
    int a = 5;
    f1(ref a);
}

public void f1(ref int a)
{
    if(a > 7) return;
    a++;
    f1(ref a);
    Co         


        
6条回答
  •  情话喂你
    2021-02-12 13:31

    Passing a value type by reference causes its position on the stack to get passed rather than the value itself. It has nothing to do with boxing and unboxing. This makes thinking about how the stack looks during the recursive calls rather easy, as every single call refers to the "same" location on the stack.

    I think a lot of confusion comes from MSDN's paragraph on boxing and unboxing:

    Boxing is name given to the process whereby a value type is converted into a reference type. When you box a variable, you are creating a reference variable that points to a new copy on the heap. The reference variable is an object, ...

    Possibly confusing you between two different things: 1) the "converting" as you will, of a value type to say an object, which is by definition a reference type:

    int a = 5;
    object b = a; // boxed into a reference type
    

    and 2) with the passing of a value type parameter by reference:

    main(){
       int a = 5;
       doWork(ref a);
    }
    void doWork(ref int a)
    {
        a++;
    }
    

    Which are two different things.

提交回复
热议问题