Out Variables in C#

Out Variables in C# 7 with examples

In this article, I am going to discuss the improvement of Out variables in C# with Examples. With the introduction of C# 7, now it is possible to define the method’s out parameters directly within the method. As part of this article, we are going to discuss the following pointers.

  1. How to work with the Out Parameter Before C# 7?
  2. Working with Out Variable in C# 7.
  3. What is the Scope of Out Parameter?
  4. Can we declare the out variable with var data type from C# 7?
  5. How to Ignore an out parameter in C#?
  6. Out Parameter Using TryParse
How to work with the Out Parameter Before C# 7?

In C#, we generally use the out parameter to pass a method argument’s reference. If you want to use an out parameter, then you need to explicitly specify the out keyword in both the calling method and method definition. Before C# 7, we need to split their declaration and usage into two parts i.e. first we need to declare a variable and then we need to pass that variable to the method using the out keyword. The Out Parameter in C# never carries value into the method definition. So, it is not required to initialize the out parameter while declaring.

Example: Out Parameter Before C# 7

Let us understand how to use Out Parameter before C# 7 with an example. Please have a look at the below example. As you can see the GetEmployeeDetails method is created with four out parameters. Then within the Main method, first we declare four variables without initializing. Initialization is optional. Then while calling the GetEmployeeDetails method, we pass the four variables by specifying the out keyword. 

class Program
{
    static void Main()
    {
        string EmployeeName, Gender, Department;
        long Salary;
        GetEmployeeDetails(out EmployeeName, out Gender, out Salary, out Department);
        Console.WriteLine("Employee Details:");
        Console.WriteLine("Name: {0}, Gender: {1}, Salary: {2}, Department: {3}",
        EmployeeName, Gender, Salary, Department);

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    static void GetEmployeeDetails(out string EmployeeName, out string Gender, out long Salary, out string Department)
    {
        EmployeeName = "Pranaya Rout";
        Gender = "Male";
        Salary = 20000;
        Department = "IT";
    }
}
Output:

OUT variables in C# 7

Note: The Out Parameter in C# never carries the value into the method definition. So, it is mandatory to initialize the out variables within the method definition otherwise you will get a compile-time error in C#. Again you cannot use the “var” data type to declare these variables.

Now, the question is, it is not required to initialize the out variables then why should we split their usage into two parts. Well, this will be overcome with C# 7.

Working with Out Variable in C# 7.

With the introduction of C# 7, now it is possible to define a method’s out parameters directly within the method. So the above program can be rewritten as shown below and also gives the same output. Here, you can see, we are directly declaring the variable at the time of method call i.e. GetEmployeeDetails(out string EmployeeName, out string Gender, out long Salary, out string Department);. This will eliminate the need to split the usage of C# out variable in two parts.

class Program
{
    static void Main()
    {
        GetEmployeeDetails(out string EmployeeName, out string Gender, out long Salary, out string Department);
        Console.WriteLine("Employee Details:");
        Console.WriteLine("Name: {0}, Gender: {1}, Salary: {2}, Department: {3}",
        EmployeeName, Gender, Salary, Department);

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    static void GetEmployeeDetails(out string EmployeeName, out string Gender, out long Salary, out string Department)
    {
        EmployeeName = "Pranaya Rout";
        Gender = "Male";
        Salary = 20000;
        Department = "IT";
    }
}

Run the application and you will get the output as expected as our previous program.

What is the Scope of Out Parameter in C#?

As we declared the out parameter directly within the method call, so we need to understand the scope of the out parameter in C#. In the above program, the out variables are in the scope of the enclosing block. So the subsequent line can use them.

Can we declare the out variable with var data type from C# 7?

Yes, you can. As the out variables are declared directly as arguments to the out parameters, so, the compiler can easily tell what their data type should be. So it is always better to use the “var” data type to declare them as shown in the following example.

class Program
{
    static void Main()
    {
        GetEmployeeDetails(out var EmployeeName, out var Gender, out var Salary, out var Department);
        Console.WriteLine("Employee Details:");
        Console.WriteLine("Name: {0}, Gender: {1}, Salary: {2}, Department: {3}",
        EmployeeName, Gender, Salary, Department);

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    static void GetEmployeeDetails(out string EmployeeName, out string Gender, out long Salary, out string Department)
    {
        EmployeeName = "Pranaya Rout";
        Gender = "Male";
        Salary = 20000;
        Department = "IT";
    }
}
How to Ignore an out parameter in C#?

If you want to ignore an out parameter then you need to use a wildcard called underscore (‘_’) as the name of the parameter. For example, if you don’t care about the Department parameter, then you just replace it with an underscore (‘_’) as shown below.

class Program
{
    static void Main()
    {
        GetEmployeeDetails(out var EmployeeName, out var Gender, out var Salary, out _);
        Console.WriteLine("Employee Details:");
        Console.WriteLine("Name: {0}, Gender: {1}, Salary: {2}",
        EmployeeName, Gender, Salary);
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    static void GetEmployeeDetails(out string EmployeeName, out string Gender, out long Salary, out string Department)
    {
        EmployeeName = "Pranaya Rout";
        Gender = "Male";
        Salary = 20000;
        Department = "IT";
    }
}

OUTPUT:

Out Parameters in C#

Out Parameter Using TryParse in C#

When we are working with real-time applications, then the common use of the out variable is the Try… pattern, where a boolean return value indicates the success, and if successful then the out parameters carry the results. Let us understand this with an example.

Example: Try Pattern using Out variable Before C# 7

Let us first see an example of using C# out variable with try pattern before C# 7. Please have a look at the following example. In the below example, first, we declare and initialize a string variable and then we declare a DateTime variable. Then within the if block we are calling the DateTime.TryParse and passing the first parameter as the string variable and the second one is the out data time parameter. If the above string is converted to DateTime, then DateTime.TryParse method will return true and the converted value will be stored in the out variable in C#.

class Program
{
    static void Main()
    {
        string s = "09-Jun-2018";
        DateTime date;
        if (DateTime.TryParse(s, out date))
        {
            Console.WriteLine(date);
        }

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
Output:

C# out Parameters

Example: Try Pattern using Out variable From C# 7

With the introduction of C# 7, the previous example can be rewritten as shown below. As you can see, now we don’t require to split the usage of the out variable into two parts. Directly we can declare the out variable within the method itself.

class Program
{
    static void Main()
    {
        string s = "09-Jun-2018";
        if (DateTime.TryParse(s, out DateTime date))
        {
            Console.WriteLine(date);
        }
        Console.WriteLine(date);
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

Run the application and it should give the same output as the previous example. In the above program, we are declaring the out variable within the method and it is being accessed from outside also. If an exception occurred, then the out variable will be assigned with a default value. Let’s see this with an example.

class Program
{
    static void Main()
    {
        string s = "09-Junnnneee-2018";
        if (DateTime.TryParse(s, out DateTime date))
        {
            Console.WriteLine(date);
        }
        Console.WriteLine(date);
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
Output:

Out Parameters Example in C#

In the next article, I am going to discuss one more interesting new feature of C# 7 i.e. Pattern Matching with Example. Here, in this article, I try to explain the improvement of Out variables in C# with Examples. I hope you enjoy this Out variable in C# with Examples article.

Leave a Reply

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