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.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...