C# 7.0 : Out Variables enhancements

In C# , we can use the out parameters to get the behavior of the call by reference. In the current version of C# , you must declare the variables before you call the method with the out parameters.

The out variables would generally be overwritten by the values within the method and hence you may not have to initialize it. In this case , you will have to specify the full type instead of using var.

For example , when you want to parse the string input to a integer using the int.TryParse method , you would use the out variable as shown in the method OutDemo1(). Note the declaration of the variable output and its type.

public static void OutDemo1()
{
    int output;
    string input = "10";
    int.TryParse(input, out output);
    Console.WriteLine(output);          
}

C# 7.0 : Out Variables enhancements

In C# 7.0 , you can declare the out variable right at the point when you pass it to the method. The function OutDemo2 demonstrates this.

// Declare variables right at the time of calling the function
public static void OutDemo2()
{
    string input = "10";
    if(int.TryParse(input, out int output))
        Console.WriteLine(output);
}

In this case , the out variable “output” is scoped to the statement they are declared in and it would work fine within the if statement.

The out variable are directly declared as parameters and hence we can use the var instead of the actual type to declare them as shown in the method OutDemo3

// out parameter with the var type

public static void OutDemo3()
{
    string input = "3";
    if (int.TryParse(input, out var output))
        Console.WriteLine(output);
}

Note that Visual Studio “15” is currently in Preview at the time of writing this blog post.

No Responses

Leave a Reply