Do int ref parameter get boxed?

后端 未结 6 1929
-上瘾入骨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:30

    It's easy to create a program that could give different results depending on whether ref int gets boxed:

    static void Main()
    {
        int a = 5;
        f(ref a, ref a);
    }
    
    static void f(ref int a, ref int b)
    {
        a = 3;
        Console.WriteLine(b);
    }
    

    What do you get? I see 3 printed.

    Boxing involves creating copies, so if ref a were boxed, the output would have been 5. Instead, both a and b are references to the original a variable in Main. If it helps, you can mostly (not entirely) think of them as pointers.

提交回复
热议问题