Using the out Modifier

The previous section introduced the ref parameter modifier, and right near the end of the presentation, it was pointed out that a ref argument must be initialized prior to it being passed to the function. The out parameter modifier is similar to the ref parameter modifier in that it causes a call-by-reference. The difference is that the out parameter modifier is used for passing information back to the caller and the argument is assumed to be uninitialized on input. The next program is a slight variation on the previous program. It uses the out parameter modifier to pass information back to the caller. The variables that the caller supplies as arguments are uninitialized.

// Out -- The out Modifier

using System;

class Program
    static void Main()
        int i, j;
        ByReference(out i, out j);
        Console.WriteLine("i = {0}, j = {1}", i, j);

    static void ByReference(out int x, out int y)
        x = 10;
        y = 20;

The output is as follows.

i = 10, j = 20

Inside a called procedure that uses an out parameter, it is assumed that the parameter is uninitialized. It is also the case that the compiler enforces the requirement that a value must be assigned to the parameter. Thus, after a call to the function, the argument will contain a valid value.

The out parameter modifier can also be applied to class types. In that case, a class reference is returned by the function.