What does "!" (exclamation) mean before a code snippet?

Asked

Viewed 17,329 times

15

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

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

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

2 answers

18

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

That is to say:

!true == false
!false == true
!(2 == 2) == false
!(2 == 1) == true
  • In this case then if periodAnterior.Equals(dataReader["PERIODNAME"]. Tostring())) is false, using the negation "becomes" true?

  • 2

    @Joaopaulo Exatamente.

  • Ah, cool, the issue now exclaimed me well.

  • Mark friend’s answer as the solution to your problem if not the question remains open.

  • It takes a while to release acceptance. Done.

11


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 keeping the result of Equals in a variable:

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

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

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

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

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

Thus, in its code, the body of if only executes if the result of periodoAnterior.Equals(dataReader["NOMEPERIODO"].ToString()) for false.


Note: Your doubt as to Equals would deserve a separate question, but probably who wrote it led to C# a Java addiction. More details and exceptions in https://stackoverflow.com/questions/1659097/c-string-equals-vs

  • 1

    Cool, I won a downvote. If there is something wrong in my reply, please let me know that I correct.

  • I thought it was cool that Joao Paulo saw that this is the most complete, accurate and best written answer for all.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.