Search code examples
c#booleanboolean-expression

What is the real meaning of if(!bool)?


I was wondering, what does exactly mean ! in the given expression :

bool myBool = AnyMethodThatReturnABoolean();
if(!myBool)
{
    // Do whatever you want
}

I now that I'm already using it when I expect myBool to be false, but is it more complex ?

Does ! mean "== false" or "!= true"?


Solution

  • It's the logical negation operator.

    The ! operator computes logical negation of its operand. That is, it produces true, if the operand evaluates to false, and false, if the operand evaluates to true.

    In your example

    if(!myBool)
    

    is like writing:

    if(myBool == false)