Home > database >  What is the correct way to write the not operator preceding the evaluation?
What is the correct way to write the not operator preceding the evaluation?

Time:01-08

The following example is clear - we evaluate the bool prior to the ! check.

bool test = a==b;
if(test) do somehting
if(!test) do something 

Suppose I want to combine the ! check and evaluation then if(!a==b) will result in comparison of !a with b.

What is the correct way to write the not operator preceding the evaluation?

The following gives error:

if !(a==b)

CodePudding user response:

What is the correct way to write the not operator preceding the evaluation?

you can try if(!(a==b))

  • But it looks complex and difficult to read, elegant way is to check if(a!=b)

Why I say elegent?

  • !(a==b) and a!= b doing the same thing, but if you want to read the condition then it will come as

!(a==b) : not a equal to b

a != b : a is not equal to b


Suppose I want to combine the ! check and evaluation then if(!a==b) will result in comparison of !a with b.. Why?

  • If you look at operator precedence table, it says !x is higher precendence than x == y.

  • This is the reason your if(!a==b) interpreting !a as first and then !a is comparing with b.


Note:

If you have multiple conditions in if condition and you want to check the negation then it is better to use

if(!(condition1 && condition2 && conditionN))

instead of

if(!condition1 || !condition2 || !conditionN)

Why?

  • As @TimSchmelter said, if you have multiple conditions then use of single ! to turn the condition to negation, help us to make our code more readable and maintainable

CodePudding user response:

Check https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/#operator-precedence for the operator precedence list in C#. The ! operator has a higher priority than the == operator, so if (!a == b) evaluates as if ((!a) == b) which is obviously not the same as if (!(a == b)).

  •  Tags:  
  • Related