Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do int ref parameter get boxed?

Tags:

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);
    Console.WriteLine(a);
}

Output is :

8 8 8 

i.e. when the stack unwinds the value of the ref parameter is maintained.

Does it mean that adding ref keyword to int parameter causes it to get boxed?
How does the actual stack look like during the recursive call?

like image 530
Pawan Mishra Avatar asked Jan 07 '15 07:01

Pawan Mishra


People also ask

Can we pass int by ref in C#?

You have to pass 0 as a reference in a variable containing 0 , for instance: int i = 0; NumberUp(ref i); Read here at MSDN for more information on the ref keyword.

How do you pass reference parameters in C#?

Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference with the intent of changing the value, use the ref , or out keyword.

What is a ref parameter?

A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.

What is the difference between a ref parameter and out parameter?

ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.


1 Answers

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.

like image 130
Allmighty Avatar answered Sep 29 '22 17:09

Allmighty