November 9th, 2007

стена, я, в профиль

Usable and beauty Enums in C#: Simple changing, simple testing

When you have some Enum in your code with flags, f.i.:

enum Options
{
    None        = 0,              // 0

    OptionOne   = 1 << 0,         // 1
    OptionTwo   = 1 << 1,         // 2
    OptionThree = 1 << 2,         // 4
    OptionFour  = 1 << 3,         // 8
    OptionFive  = 1 << 4,         // 16

    All         = (1 << 5) - 1    // 31 = 32 - 1 = 2 ^ 5 - 1
}



And want to test it easy, use class like this:

public class Enum<T>
{
    int Flags;
    int Flag;
    
    public Enum (T flags)
    {
        Flags = Convert.ToInt32(flags);
    }

    public bool Contains (T flag)
    {
        Flag = Convert.ToInt32(flag);
        return ((Flags & Flag) == Flag);
    }
}



And somewhere in your code you just do it like this:

Options someConcreteOptionSet;
// We set it here just for example.
// In real life this is just some
// method param.
someConcreteOptionSet = Options.OptionFour | Options.OptionTwo;
Enum<Options> o = new Enum<Options>(someConcreteOptionSet);

if (o.Contains(Options.None))
    Response.Write(Options.None + "\r\n");
if (o.Contains(Options.OptionOne))
    Response.Write(Options.OptionOne + "\r\n");
if (o.Contains(Options.OptionTwo))
    Response.Write(Options.OptionTwo + "\r\n");
if (o.Contains(Options.OptionThree))
    Response.Write(Options.OptionThree + "\r\n");
if (o.Contains(Options.OptionFour))
    Response.Write(Options.OptionFour + "\r\n");
if (o.Contains(Options.OptionFive))
    Response.Write(Options.OptionFive + "\r\n");
if (o.Contains(Options.All))
    Response.Write(Options.All + "\r\n");



Instead of "Response.Write" you could use "Console.Write" to test the behaviour.

When you want to add OptionSix, you just do it like:

enum Options
{
    None        = 0,              // 0

    OptionOne   = 1 << 0,         // 1
    OptionTwo   = 1 << 1,         // 2
    OptionThree = 1 << 2,         // 4
    OptionFour  = 1 << 3,         // 8
    OptionFive  = 1 << 4,         // 16
    OptionSix   = 1 << 5,         // 32

    All         = (1 << 6) - 1    // 63 = 64 - 1 = 2 ^ 6 - 1
}



Pay attention to both OptionSix and All - only there you must add/change something.