Information Technology Reference
In-Depth Information
Output Parameters
Output parameters
are used to pass data from inside the method back out to the calling code.
They are very similar to reference parameters. Like reference parameters, output parameters
have the following requirements:
You must use a modifier in both the method declaration and the invocation. With out-
put parameters, the modifier is
out
, rather than
ref
.
The actual parameter
must
be a variable—it cannot be another type of expression.
For example, the following code declares a method called
MyMethod
, which takes a single
output parameter.
out modifier
↓
void MyMethod( out int val ) // Method declaration
{ ... }
...
int y = 1; // Variable for the actual parameter
MyMethod ( out y ); // Method call
↑
out modifier
Like reference parameters, the formal parameters act as aliases for the actual parameters.
Both the formal parameter and the actual parameter are names for the same memory location.
Clearly, any changes made to a formal parameter in the method will be visible through the
actual parameter variable after the method.
Unlike reference parameters, output parameters require the following:
Before the method call, you do not have to initialize or assign values to the actual param-
eter variables. The initial values of the actual parameters are irrelevant.
Inside the method, an output parameter must be assigned to, before it can be read from.
Every output parameter
must be assigned to
, before the method exits.