0

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"?

Zoma
  • 321
  • 7
  • 20

3 Answers3

2

It simply inverts the value of the bool expression.

True becomes False and False becomes True.

if block will run only if expression inside the parentheses evaulates to True.

AgentFire
  • 8,944
  • 8
  • 43
  • 90
2

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)
Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
1

it's the same as:

if(mybool == false){ 

      //some code
}

Just a shorthand way of writing it.

Nick
  • 3,454
  • 6
  • 33
  • 56