Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the code get compiled when I use !!= C#

Tags:

c#

I am trying to understand how does the code get compiled when I use (!!=) Apparently the 2 snippets below do the same thing. Why are both permissable?

if (4 !!= 5)
  Console.WriteLine("vvvvvv");

the above does the same thing as:

if (4 != 5)
   Console.WriteLine("vvvvvv");
like image 786
Erik_JI Avatar asked Jul 15 '26 00:07

Erik_JI


1 Answers

The expression 4 !!= 5 is parsed as the null-forgiving operator applied to 4, and then != applied to that expression and 5. That is, (4!) != 5.

According to the draft spec, a null forgiving expression is a kind of primary expression:

primary_expression
    : ...
    | null_forgiving_expression
    ;

null_forgiving_expression
    : primary_expression '!'
    ;

and that:

The postfix ! operator has no runtime effect - it evaluates to the result of the underlying expression. Its only role is to change the null state of the expression to "not null", and to limit warnings given on its use.

In other words, the ! after 4 does nothing and is very redundant. The constant 4 is never null after all :)

like image 93
Sweeper Avatar answered Jul 17 '26 14:07

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!