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
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 .
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.
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.
The inequality operator != returns true if its operands are not equal, false otherwise. For the operands of the built-in types, the expression x !=
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With