Negating the 'is' operator with a variable only works with '!' but not with '== false'

Viewed 339

Why does (expr is type varname) == false gives a compile error, but !(expr is type varname) compiles?

public static void Foo(object o)
{
    if(!(o is string s))  // <-- Using '!'
    {
        return;
    }
    
    Console.WriteLine(s);  // <-- OK
    
}
public static void Bar(object o)
{
    if((o is string s) == false) // <-- Using '== false'
    {
        return;
    }
    
    Console.WriteLine(s);  // <--Error: Use of unassigned local variable 's'
}

Live example: https://dotnetfiddle.net/nYF7b6

1 Answers

The compiler isn't (yet) smart enough to spot this case: it doesn't factor things like == false into the definite assignment analysis.

This has been proposed by one of the language design team however (see also the linked issues there). It looks like they're currently planning to cover this in C# 10.

Related