I'm trying to understand what the C# compiler's rules are for deciding when an out variable was assigned.
Here's one example that baffles me. Let's assume we have a Dictionary<>:
var dict = new Dictionary<string, string>();
Let's start with a simple condition: this compiles.
var found = dict.TryGetValue("b", out var val);
if(found)
{
Console.WriteLine(val); //no problem
}
If the condition is slightly more complicated, it's a compile error:
var aBool = true;
var found = aBool && dict.TryGetValue("b", out var val);
if(found)
{
Console.WriteLine(val); //use of unassigned local variable val
}
OK, so I guess the compiler doesn't deal with logical operators in this case.
...but if we move the exact same condition inline, it's all rainbows again:
var aBool = true;
if(aBool && dict.TryGetValue("b", out var val))
{
Console.WriteLine(val); //compiles fine
}
Why?