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)anda!= bdoing the same thing, but if you want to read the condition then it will come as
!(a==b): notaequal tob
a != b:ais not equal tob
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
!xis higher precendence thanx == y.This is the reason your
if(!a==b)interpreting!aas first and then!ais comparing withb.
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)).
