Search code examples
c#xor

C# - Check a bool for a value and then flip it


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

I wanted to know if there's a way of flipping checkedDB in the same statement, i.e. the next iteration checkedDB is the opposite of it's value, so like XORing.


Solution

  • What about:

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

    That may be not really readable/understandable at first sight, but it does what you want in one statement.