Clearing Enum Flags

UPDATE: It looks like I am confusing a lot of people with this article. I wanted to write an article about something else than the title suggests (how flags enum are built) but I did not explain it well and what’s more important I forgot to mention the most important thing: how to simply clear a flag. I apologize for the confusion and here is the simple way of just clearing a flag:

[Flags]

public enum Foos {

    A = 1,

    B = 2,

    C = 4,

    D = 8,

    AB = A | B,

    CD = C | D,

    All = AB | CD

}

 

static class Program {

    static void Main() {

        Foos value = Foos.AB;

        Console.WriteLine(ClearFlag(value,Foos.A);

    }

    public static Foos ClearFlag(Foos value, Foos flag) {

       return value & ~flag;

    }

}

… I will try to write the other article some other time :-)

Published 29 August 06 09:49 by kcwalina

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Thomas Scheidegger MVP said on August 29, 2006 4:49 PM:
Maybe there are side-effects, but the easiest C# version is:

public static Foos ClearFlag( Foos value, Foos flag )
{
 value &= ~flag;
 return value;
}
# Brenton House said on August 29, 2006 9:31 PM:
Clearing Enum Flags Via Krzysztof Cwalina - Somebodyjust pointed out to me that the enum guidelines don’t
# Omer van Kloeten said on August 29, 2006 11:54 PM:
This is the first time I've seen someone xor the enum instead of and-not it, like Thomas shows.
Why is this better?
# Refines.Info["Polo Lee"] said on February 12, 2007 7:57 PM:

為什麼推薦 ? Krzysztof Cwalina 是 .NET Framework API Design Team 的 Program Manager, 他也寫了 一本 Framework Design

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Page view tracker