Out Parameters

The out keyword causes values to be passed by reference, this is very much like the ref keyword but variables do not have to be initialised first. To use out parameters, both the method definition and calling method must explicitly use the out keyword.

public class Program
{
    private static void Main(string[] args)
    {
        int foo;

        MyFunction(out foo);
    }

    private static void MyFunction(out int foo)
    {
        foo = 10;
    }
}

A couple of things should be noted:

  • The called method must always assign a value to the out parameter before the function returns.
  • Properties cannot be passed as out parameters since they are not variables.
  • Async functions defined with the async modifier cannot accept out parameters.
  • Iterator functions which include a yield return or yield break statement can also not accept out parameters.

Declaring out parameters is most useful when you would like a function to be able to return multiple values. A function that uses out parameters can still return a value as its return type but it can also return one or more objects to a calling method as out parameters.

public class Program
{
    static void Main(string[] args)
    {
        int foo;
        double bar;

        bool result = MyFunction(24, out foo, out bar);
    }

    private static bool MyFunction(int input, out int foo, out double bar)
    {
        if (input > 10)
        {
            foo = input * 10;
            bar = input / 2.5;

            return true;
        }
        else
        {
            foo = 0;
            bar = 0;
        }

        return false;
    }
}

Leave a comment