Why are out parameters inside an if statement condition not local to the if block? [Answered]

if (dictionary.TryGetValue(key, out var val))
{

}

// why can I access val here?
if (dictionary.TryGetValue(key, out var val))
{

}

// why can I access val here?
Is this because of how it ends up compiling val above the if statement?
7 Replies
333fred
333fred3y ago
You can access val there because the if (!TryGetValue) return; pattern is super common in .NET, and we wanted that pattern to work with out variable declarations
nathanAjacobs
nathanAjacobsOP3y ago
I see, so in that case when it fails, you wouldn't have to call it again to access the out parameters. That makes sense. Thanks!
333fred
333fred3y ago
Or declare them ahead of time, like
int i;
if (!TryGetValue(out i)) return;
// Do something with i
int i;
if (!TryGetValue(out i)) return;
// Do something with i
nathanAjacobs
nathanAjacobsOP3y ago
I feel like that's more explicit, but I can see how that could get annoying.
333fred
333fred3y ago
Well, that was the old way But C# 6 (iirc) added inline out variable declaration, and we wanted it to work for all scenarios The leaky scoping was controversial, but imo for the best
nathanAjacobs
nathanAjacobsOP3y ago
Ahh didn't know it used to be like that. If it was to make it work for all scenarios, then I totally agree.
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server