The only difference is a compiler hint.
... out ...
public static void TestOut(out int test)
{
test = 1;
}
.method public hidebysig static void TestOut([out] int32& test) cil managed
{
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: stind.i4
IL_0003: ret
} // end of method Program::TestOut
... ref ...
public static void TestRef(ref int test)
{
test = 1;
}
.method public hidebysig static void TestRef(int32& test) cil managed
{
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: stind.i4
IL_0003: ret
} // end of method Program::TestRef
... out
and ref
are effectively the same. The only real difference being that out tells the compiler to expect the value to be set before the method is returned. You could send a value to a function that has an out
flag but again the compiler will treat it as an unassigned variable. The runtime doesn't really care. Both will be created as a pointer to the variable. You are best to use the keyword that describes the functionality you expect with your function. Any optimization that "may" take place in the JITer below this will have near 0 impact on the application.