By reference means you can change the original variable passed to the item. It basically passes the address of the variable on the stack rather than the variable value.
IL Dump:
As you actually asked what actually happens on the stack here is an IL dump of a by ref and by value method:
.method private hidebysig instance void ByRef(string& s) cil managed
{
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldstr "New value"
IL_0007: stind.ref
IL_0008: ret
} // end of method Class1::ByRef
vs.
.method private hidebysig instance void ByValue(string s) cil managed
{
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "New value"
IL_0006: starg.s s
IL_0008: ret
} // end of method Class1::ByValue
As you can see the main difference is the parameter type (string&
instead of string
) and that it does extra steps to load and store the values indirectly.
The simple C# source is shown below for reference:
void ByRef(ref string s)
{
s = "New value";
}
void ByValue(string s)
{
s = "New value";
}