Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the value of a C# 'out' or 'ref' parameter actually returned to the caller?

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?
}
like image 296
Zach Johnson Avatar asked Jan 07 '10 23:01

Zach Johnson


People also ask

What is a value of C?

The c-value is where the graph intersects the y-axis. In this graph, the c-value is -1, and its vertex is the highest point on the graph known as a maximum. The graph of a parabola that opens up looks like this. The c-value is where the graph intersects the y-axis.

What is the value of C if 8 is 4?

Answer: The required value of c is 0.25.

How do you work out the value of C?

Whenever you are trying to find the missing C-value, always remember the following formula: (b/2)^2. This formula will allow to find the missing C-value in your standard form equation.


1 Answers

Since ref and out parameters 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 ArgumentException of course), outValue and refValue would both be set to 2.

It is also important to note that out and ref are identical concepts at an IL level - it is only the C# compiler that enforces the extra rule for out that requires that a method set its value prior to returning. So from an CLR perspective outValue and refValue have identical semantics and are treated the same way.

like image 140
Andrew Hare Avatar answered Oct 15 '22 00:10

Andrew Hare