Search code examples
c#if-statementinitializationpattern-matchinglocal-variables

Why local variable in C# must be initialized after initializing and cast inside If operator condition?


public void A()
{
    if (!(_s is string v))
        return;

    Console.WriteLine(v);
}

This code compiles good
But

public void A()
{
    if (false == _s is string v)
        return;

    Console.WriteLine(v); <-- 'Local variable 'v' might not be initialized before accessing'
}

But this returns compiler error
What's the reason?


Solution

  • The flow analysis isn't perfect.

    if (true == _s is string v)
      Console.WriteLine(v); 
    

    also fails.

    Definite assignment flow analysis is conservative - its purpose is to make sure you can't read an unassigned local. It's desirable for it to also be able to figure out branches that can never be reached given a set of conditions, but that's a bonus.

    In the end, you would need to do a specific analysis to handle the case of false == _s is string v. But why, when there's no reason not to use !(_s is string), which is handled just fine? You can always do the analyzer more complicated, but there's also a value to keeping it simple.