Thursday, November 20, 2008

C# .NET Method Parameter Modifiers (The out Modifier)

In a previous post I told about 4 method parameter modifiers of C#. The out modifier is one of them. In this post, I am going to tell about it and its purpose.

Methods that have been defined to take output parameters are under obligation to assign them to an appropriate value before exiting the method in question (if you fail to ensure this, you will receive compiler errors).

To illustrate, consider the Add() method that returns the sum of two integers using the C# out modifier (note the physical return value of this method is now void):

// Output parameters are allocated by the member.
public 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. 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)
{// No need to assign local output variables.
int ans;Add(90, 90, out ans);
Console.WriteLine("90 + 90 = {0} ", ans);
}

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.

// Returning multiple output parameters.
public static void FillTheseValues(out int a, out string b, out bool c)
{
a = 9; b = "Enjoy your string."; c = true;
}

The caller would be able to invoke the following method:

static void Main(string[] args)
{
int i;
string str;
bool b;
FillTheseValues(out i, out str, out b);
Console.WriteLine("Int is: {0}", i);
Console.WriteLine("String is: {0}", str);
Console.WriteLine("Boolean is: {0}", b);
}

No comments: