C# 7.0 – #1. New out parameter usage

In C# 7.0 using an out variable is simpler than in older version of the language.
In a nutshell an out variable doesn’t need to be declared anymore before its usage, but can be inline declared just before use it, as shown here:


var n = "2";
//pre-declaration for out parameter variable isn't required anymore
//int p;
//inline declaration for out parameter variable.
int.TryParse(n, out int p);
Console.WriteLine(p);

Furthermore, it’s possible to use the var keyword to inline declare the variable, and not the specific type only, as you would do with C# 6.0 with not initialised pre-declared variables.


var n = "2";
int.TryParse(n, out var p2);
Console.WriteLine(p2);

The inline declared out variables are in scope with the code block that contain them, then they can be used after the declaration inside that block.

If you don’t care about some out function parameter you can complitely ignore them by using wildcards (the “_” symbol).


var n = "2";
int.TryParse(n, out int _);

Leave a Reply

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