Out Variables in C#

Out variables are not my go to variables because I rarely write in a way where I have to use out variables. But for some developer this is somewhat of a daily bread, specially if they are dealing with old libraries. I’m not saying that’s the only way you may use them. In some cases makes perfect sense the use of out variables. Like parsing a value with the old timer tryparse.

In C# 7.x, one of the updates to the language was out variables. Basically you can have a simply way to declare and use it.

if (int.TryParse(input, out var answer))
    Console.WriteLine("Could not parse input");

In the example above we can see how to use out variables in a real live case. Now, you can declare out variable in-line, right after the out keyword. One minor negative thing, if you want to called that way, is that now you need to be a bit more aware of the scope of a out variable. There are several positive things, here are a couple. One, it's easy to read the type of your variable. You don't need to have an initial value.

There you go. A simple update to the language that help us to be more productive and to write better code. I mean you no longer have to write that extra variable in order to capture a out variable and the scope of the out variable is bound to the time where is declare inline.



Spread the word
  • Yum