简体   繁体   中英

Why does the code get compiled when I use !!= 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");

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 :)

This only works in C# 8.0 and later. See null-forgiving .

I believe you are just stating that 4 could be null and telling the compiler that it should not show errors if 4 does happen to be null.

To complement other answers - in case you don't understand something about what is happening in terms of compilation you can use tools such decompilers - for example an online one - https://sharplab.io/ . Among the others capabilities it provides ability to see the decompiled to IL (not very useful here), C# (basically desugared version of the code, for this one - see , also not very useful here) and also syntax tree (for this one - see ), which can be useful in this particular case. I've used next code (so it can be compiled in release mode without optimizing constants out):

public class C {
    public void M(int? i) {
        if (i !!= 5)
            Console.WriteLine("vvvvvv");
    }
}

If you expand CompilationUnit -> ClassDeclaration -> MethodDeclaration -> Body -> IfStatement -> Condition -> Left you will see that it is actually SuppressNullableWarningExpression with operand being i :

在此处输入图像描述

在此处输入图像描述

With sharplab.io kindly highlighting the part of the code which is represented by selected syntax node. So as others described you can see that compiler parses your code as 4 followed by null-forgiving operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM