haw8da
Last Updated: February 25, 2016
·
581
· keboo

Check for composite enum values

Assume that you are worked with a flagged enum value. Perhaps something like this:

[Flags]
enum FinishTypes
{
    None = 0,
    Gold = 1,
    Silver = 2,
    Bronse = 4,
    Medals = Gold | Silver | Bronse,
    FirstRunnerUp = 8,
    SecondRunnerUp = 16,
    FirstLosers = FirstRunnerUp | SecondRunnerUp,
    All = Medals | FirstLosers
}

We want to write a method that returns a boolean indicating if the passed value is made up of a single value, or multiple items from the enum. In our case, we would expect true to be returned for FinishTypes values of Medals, FirstLosers, and All or any bitwise combination of values.

private static bool IsComposite(FinishTypes finisherType)
{
    //code?
}

Before looking at one possible solution, give it a shot. There are multiple (correct) ways to solve this.

There are two pieces to solving this problem. First enum values are just named integers (unless you specify a different integral type 1). Second, the problem is simply checking if a value is a power of two.

Here is one possible solution along with a simple Main to test the output:

private static bool IsComposite(FinishTypes finisherType)
{
    return finisherType != FinishTypes.None &&
            ((int)finisherType & ((int)finisherType - 1)) != 0;
}

static void Main()
{
    foreach (var value in Enum.GetValues(typeof(FinishTypes)).Cast<FinishTypes>())
    {
        Console.WriteLine("{0}: Is Composite? {1}", value, IsComposite(value));
    }
    Console.ReadLine();
}

There are several methods for checking if a number if a power of two 2. The above algorithm uses the decrement and compare method (See 2)

Source: http://dotnetgeek.tumblr.com/post/34211704003/check-for-composite-enum-values

Say Thanks
Respond