Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 330
ZivS Avatar asked Feb 06 '21 20:02

ZivS


People also ask

What does '!' Mean in JavaScript?

The ! symbol is used to indicate whether the expression defined is false or not. For example, !( 5==4) would return true , since 5 is not equal to 4. The equivalent in English would be not .

What is&= operator in c#?

The &= operator concatenates the String expression on its right to the String variable or property on its left, and assigns the result to the variable or property on its left.

What does {} mean in JavaScript?

So, what is the meaning of {} in JavaScript? In JavaScript, we use {} braces for creating an empty object. You can think of this as the basis for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array.

How do you write does not equal in C#?

The inequality operator != returns true if its operands are not equal, false otherwise. For the operands of the built-in types, the expression x !=


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.

like image 132
canton7 Avatar answered Oct 31 '22 02:10

canton7