When I make an assignment to an out or ref parameter, is the value immediately assigned to the reference provided by the caller, or are the out and ref parameter values assigned to the references when the method returns? If the method throws an exception, are the values returned?
For example:
int callerOutValue = 1;
int callerRefValue = 1;
MyMethod(123456, out callerOutValue, ref callerRefValue);
bool MyMethod(int inValue, out int outValue, ref int refValue)
{
outValue = 2;
refValue = 2;
throw new ArgumentException();
// Is callerOutValue 1 or 2?
// Is callerRefValue 1 or 2?
}
Since
refandoutparameters allow a method to work with the actual references that the caller passed in, all changes to those references are reflected immediately to the caller when control is returned.This means in your example above (if you were to catch the
ArgumentExceptionof course),outValueandrefValuewould both be set to 2.It is also important to note that
outandrefare identical concepts at an IL level - it is only the C# compiler that enforces the extra rule foroutthat requires that a method set its value prior to returning. So from an CLR perspectiveoutValueandrefValuehave identical semantics and are treated the same way.