What does "!" mean before a code snippet?

14

There are many basic things that I do not know, for example how to read exactly this exclamation in the following way:

if (!(periodoAnterior.Equals(dataReader["NOMEPERIODO"].ToString()))){
    //...
}

Can anyone explain me? And taking advantage, does this Equals do the same as "=="?

    
asked by anonymous 25.04.2014 / 19:16

2 answers

10

Anything you put inside a if(aqui) will be transformed into true or false . The body of if only executes if the result is true .

Let's simplify your example by saving the result of Equals to a variable:

bool resultado = periodoAnterior.Equals(dataReader["NOMEPERIODO"].ToString());

The variable resultado contains true or false . So we have two options for if :

if (!(true)) {}
if (!(false)) {}

What the exclamation ! does is to invert the value of a boolean: !true (reads "not true") is false , and !false is true . Therefore, the possible results for if will be:

if(false) {} // aqui o corpo nunca executa
if(true) {} // aqui o corpo executa

So, in your code, the body of if only executes if the result of periodoAnterior.Equals(dataReader["NOMEPERIODO"].ToString()) is false .

Note: Your doubt about Equals deserves a separate question, but probably who wrote that led to C # a Java addiction. More details and exceptions on link

    
26.04.2014 / 01:01
17

! is the negation operator. It returns the opposite of the resolution of the operation it precedes.

That is:

!true == false
!false == true
!(2 == 2) == false
!(2 == 1) == true
    
25.04.2014 / 19:18