out keyword in C#


The out keyword can be used with variables and method parameters. The out paramters are always passed by reference for both, the value type and the reference type data types.

Declare Method with Out Parameter

The out keyword can be used with the variable declaration or method parameters.

Syntax:
out <data type> <variable name>;

<method name>(out <data type> <parameter name>)

The following example demonstrates the method declaration with out parameters.

Example: Method with out Parameter
public static void OutParamExample(out int x){
    x = 100;
}

The above example defines the OutParamExample() method with one out parameter x. The out keyword is applied before the type and name of a parameter.

Calling Method with Out Parameter

The variable must be declared without initializing before calling a method that includes the out parameters. Also, while calling the method, a variable must be passed with out keyword.

Example: out Parameter
int a; // declare variable without initialization

OutParamExample(out a);// calling method with out keyword

Console.Write(a);// accessing out parameter value

public static void OutParamExample(out int x){
    x = 100;
}

C# 7 introduced a new way of declaring the out parameters. In C# 7 onwards, you don't need to declare out variable before passing to parameters. It can now be declared while calling the method.

Example: out Parameter in C# 7
OutParamExample(out int a);// declare out variable while calling method
Console.Write(a);// accessing out parameter value

public static void OutParamExample(out int x){
    x = 100;
}

When to use out parameters?

The out parameters can be used when you want to return more than one values from the method.

The following example demonstrates getting two random numbers from the single method call.

Example: out Keyword Usage
public static void GetMultipleRandomValue(out int x, out int y)
{
    var random = new Random();
    x = random.Next();
    y = random.Next();
}

public static void Main()
{
    int random1, random2;
    GetMultipleRandomValue(out random1, out random2);

    Console.WriteLine($"{random1}, {random2}");
}

The out parameters can be used to remove the possibility of the return null value. C# uses it effectively in built-in TryParse methods. C# has Parse() and TryParse() methods for int, float, char, and bool data types. The difference between Parse() and TryParse() methods are that the Parse() method can throw an exception whereas TryParse() method will never throw an exception because it uses out parameter to which the valid value will be assigned if successful. Check how the TryParse() method uses out parameter while converting string to int.

Related Articles