// Output parameters must be assigned by the called method.
static void Add(int x, int y, out int ans)
{
ans = x + y;
}
Calling a method with output parameters also requires the use of the out modifier. Recall that
local variables passed as output variables are not required to be assigned before use (if you do so,
the original value is lost after the call), for example:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
...
// No need to assign initial value to local variables
// used as output parameters.
int ans;
Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0}", ans);
Console.ReadLine();
}
The previous example is intended to be illustrative in nature; you really have no reason to
return the value of your summation using an output parameter. However, the C# out modifier
does serve a very useful purpose: it allows the caller to obtain multiple return values from a single
method invocation.
Do'stlaringiz bilan baham: |