How to group Enum values?

I can add a Utility class with static member like IsADarkColor(Colors c). But I would like do it without an additional class because I could forget that related class when I need that feature.

This is when Extension Methods come in handy:

// Taking Reed Copsey's naming advice
public enum Color
{
    LightBlue,
    LightGreen,
    DarkGreen,
    Black,
    White,
    LightGray,
    Yellow
}

public static class Colors
{
    public static bool IsLightColor(this Color color)
    {
        switch(color){
            case Color.LightBlue:
            case Color.LightGreen:
            case Color.DarkGreen:
            case Color.LightGray:
            return true;
            default: 
            return false;
        }
    }
}

As long as these two classes are in the same namespace, you can see the static method as if it belonged to the Color class:

var color = Color.LightBlue;
if(color.IsLightColor()) {...}

(hat tip to @Abdul for making me think of extension methods)


You will need to write this in a class.

Personally, I would recommend reworking this into a Color (singular) enum, and a Colors class. The Colors class could then include methods or properties which return "groups" of enums (ie: IEnumerable<Color> LightColors { get { //...)


Simple groupings like this can be managed with Flags and some bitwise math.

    public class Program
    {
        public static void Main()
        {
            var test = Colors.Red;

            var isWarm = Constants.WarmColors.HasFlag(test);
            var isCool = Constants.CoolColors.HasFlag(test);

            Console.WriteLine(isWarm);  //true
            Console.WriteLine(isCool);  //false
        }

        public static class Constants
        {
            public static Colors CoolColors = Colors.Green | Colors.Blue | Colors.Purple;
            public static Colors WarmColors = Colors.Red | Colors.Orange | Colors.Yellow;
        }

        [Flags]
        public enum Colors
        {
            White = 0,
            Red = 1,
            Orange = 1 << 1,
            Yellow = 1 << 2,
            Green = 1 << 3,
            Blue = 1 << 4,
            Purple = 1 << 5,
            Brown = 1 << 6,
            Black = 1 << 7
        }
    }

Bitwise and shift operators (C# reference) --Microsoft)

Logical and Bitwise Operators in C# -- Dániel Szabó/Plural Sight

Tags:

C#