Information Technology Reference
In-Depth Information
Since the code inside the method must write to an output variable before it can read from
it, it is impossible to send data
into
a method by using output parameters. As a matter of fact, if
there is any execution path through the method that attempts to read the value of an output
parameter before the method has assigned it a value, the compiler produces an error message.
↓
↓
public void Add2( out int InRef )
{
int var1 = InRef + 2; // Error! Cannot read from an output variable
}
↑
// before it has been assigned to by the method.
For example, the following code again shows method
MyMethod
, but this time using output
parameters.
class MyClass
{ public int Val = 20; } // Initialize field to 20.
class Program
out modifier
out modifier
{
↓
↓
static void MyMethod(out MyClass f1, out int f2)
{
f1 = new MyClass(); // Create an object of the class.
f1.Val = 25; // Assign to the class field.
f2 = 15; // Assign to the int param.
}
static void Main()
{
MyClass A1 = null;
int A2;
MyMethod(out A1, out A2); // Call the method.
}
↑
↑
}
out modifiers