C# 7.0 – Out variables 1


Facebooktwittergoogle_pluslinkedinmail

Using out parameters was always a bit painful. The biggest drawback is the need to declare variables before they can be used.

Note: You can view all code examples on GitHub. My environment: Visual Studio 2017 (15.7.5) and .NET Framework 4.6.1.

In C# usually variable is declared when it’s needed.

        private void Example1()
        {
            var name = "some name";
        }

But for out variables the story is different. You have to first predeclare a variable to use it later.

        // Let's assume we want to call the following method
        private void GetName(out string name) => name = "James Tiberius Kirk";

        private void Example2()
        {
            string name;
            GetName(out name);
            Console.WriteLine(name);
        }

Fortunately, it was changed in C# 7.0. Now it’s possible to declare an out variable when it’s needed.

            GetName(out string name);

Note that the scope of an out variable is the enclosing block. This way the variable can be used later.

        private void Example3()
        {
            GetName(out string name);
            Console.WriteLine(name);
        }

It’s also allowed to use var keyword as the compiler will be able to tell the type (unless there are conflicting overrides).

        private void Example4()
        {
            GetName(out var name);
            Console.WriteLine(name);
        }

A very common pattern for out parameters is the TryParse pattern. With out variables, the TryParse lucks more concrete.

        void PrintFutureAge(string ageAsString)
        {
            if (int.TryParse(ageAsString, out var age))
            {
                Console.WriteLine($"In 10 years a person will be {age + 10} years old");
            }
        }

This is one of my favorite improvements in C# 7.0. I find the new way more cohesive and just nicer for my eyes.

 

Facebooktwittergoogle_pluslinkedinmail

Leave a comment

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

One thought on “C# 7.0 – Out variables