C # - Check bool value and then flip it

for (int i = 0; i < X; i++)
   myitem = (checkedDB) ? dirtyItem : cleanItem;

I wanted to know if there is a way to flip checkedDB in the same statement, i.e. the next iteration of checkedDB is the opposite of this value, just like XORing.

+3
source share
3 answers

What about:

for (int i = 0; i < X; i++)
    myitem = !(checkedDB = !checkedDB) ? dirtyItem : cleanItem;

It may not be completely clear and understandable at first glance, but it does what you want in one statement.

+6
source

The best answer, IMO, is: no, if you have self-esteem. The result will be ugly and confusing, and there will be no real gain. Here are two different solutions that are cleaner and therefore easier to understand.

for (int i = 0; i < X; i++)
{
    myitem = checkedDB ? dirtyItem : cleanItem;
    checkedDB = !checkedDB;
}

:

for (int i = 0; i < X; i++)
{
    myitem = i%2 == 0 ? dirtyItem : cleanItem;
}
+3

- bool ^= true:

for (int i = 0; i < X; i++)
{
   myitem = (checkedDB ^= true) ? cleanItem : dirtyItem;
}

cleanItem dirtyItem, checkedDB , .

The advantage of using checkedDb ^= trueover checkedDB = !checkedDBis that it is clear that you wanted to change checkedDBand it was no coincidence that the comparison was wrong ==.

Since you did not specify the language, I cannot say for sure whether your language will allow assignment in the conditional part of the ternary operator.

0
source

Source: https://habr.com/ru/post/1743591/


All Articles