Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a value using the ref keyword

Tags:

c#

parameters

ref

After reading the MSDN article on the ref keyword, I am confused as to what C# does when you pass a value type using the ref keyword. The documentation states that the ValueTypes are not boxed. My question is how does C# handle passing a value type as a reference? Is it passing some copy to the data that is allocated on the Stack? Thanks.

like image 410
wonbyte Avatar asked Dec 12 '13 19:12

wonbyte


1 Answers

Is it passing some copy to the data that is allocated on the Stack?

No, it does not make a copy. ref and out keyword can be compared to passing by pointer in C or passing by reference in C++, when the memory location (i.e. an address) of the variable is passed to the target method. The method that takes a reference would then modify the value directly in place using the memory location passed in.

Knowing that the variable is passed by reference, compiler inserts instructions that treat the ref variable as an address, allowing in-place modifications.

like image 107
Sergey Kalinichenko Avatar answered Sep 26 '22 22:09

Sergey Kalinichenko