Search code examples
c#bitwise-operators

How to remove option from bit wise operation


I am working in a WPF app where I have some Items checked, I am trying to clear the checked items and reset it in the for loop if the is check is true. Using ' fruit.FruitType = NewFruitType.None;' after running the loop the selection is still NONE. If I remove' fruit.FruitType = NewFruitType.None;' it keeps all items and don't remove the Items that were unchecked.

Item1 | item2 | item3| item4

If item 3 and 4 are removed how can I have the selection be Item1 | item2?

 fruit.FruitType = NewFruitType.None;

 foreach (var fruitType in fruit.FruitTypes.Where(x => x.IsChecked))
 {
     contact.FruitType |= (NewFruitType)fruitType.Id;
 }

Solution

  • You need to use AND NOT (technically "and complement of") logic. In C# syntax that is &= and ~ for bitwise operations.

    Try this:

    var stuff = Items.Item1 | Items.Item2 | Items.Item3 | Items.Item4;
    Console.WriteLine(stuff);
    
    stuff &= ~Items.Item2; 
    Console.WriteLine(stuff);
    

    result:

    Item1, Item2, Item3, Item4
    Item1, Item3, Item4
    

    If you wanted to remove multiple at once, you need to continue anding:

    var stuff = Items.Item1 | Items.Item2 | Items.Item3 | Items.Item4;
    Console.WriteLine(stuff);
    
    stuff &= ~Items.Item2 & ~Items.Item3; 
    Console.WriteLine(stuff);
    

    result:

    Item1, Item2, Item3, Item4
    Item1, Item4
    

    This should also work even if the initial list does not include the removed flags:

    var stuff = Items.Item1 | Items.Item3 | Items.Item4;
    Console.WriteLine(stuff);
    
    stuff &= ~Items.Item2 & ~Items.Item3; 
    Console.WriteLine(stuff);
    

    result

    Item1, Item3, Item4
    Item1, Item4
    

    Check out the details in Microsoft's reference here: Bitwise and shift operators (C# reference)