In C#7 there is an improvement on using out parameter. Some of you may remember writing code like below.
string hourString = "5";
int hour;
if (int.TryParse(hourString, out hour))
{
Console.WriteLine($"The hour is {hour}");
}
The improvement that C#7 brings is you can now declare out variables in the argument list of a method call, rather than writing a separate declaration statement like below:
string hourString = "5";
if (int.TryParse(hourString, out int hour))
{
Console.WriteLine($"The hour is {hour}");
}
And it doesn’t end there we can also use the var keyword if we choose to.
string hourString = "5";
if (int.TryParse(hourString, out var hour))
{
Console.WriteLine($"The hour is {hour}");
}
Summary
What are the benefits of this out parameter, well it does make the code is easier to read. You are not declaring it where you use it. Not to mention you don’t need to initialize the variable either.