skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

Declare out variables inline

C# 7

C# code using int.TryParse with an inline out var and a discard, printing Parsed 84 and Not a number.

Declare out var at the call. Use _ to discard values you ignore. Declare out variables inline and discard the ones you don't need. It is available since C# 7. The key line is if (int.TryParse(input, out var n)) in out-variables.cs. Run it and the output reads Parsed 84, Not a number.

Did this tip save you some time? Consider buying me a coffee to fuel the next one.

Buy me a coffee
Railway Referral

Need somewhere to deploy?

My link gets you $20 in credits.

Claim $20 credit

I may earn a commission if you become a customer.

out-variables.cs
var input = "42";
if (int.TryParse(input, out var n))
Console.WriteLine($"Parsed {n * 2}");
if (!int.TryParse("abc", out _))
Console.WriteLine("Not a number");
Output
$ dotnet run out-variables.cs
Parsed 84
Not a number