Search code examples
c#listenumsenum-flags

Store multiple true values with an enum


I have recently started using enums to more efficiently store information in a database. I was wondering if there is some way to use them to store multiple true values. To elaborate, in a enum such as GenderEnum I would store male as 0, female as 1, OtherUnclear as 3 in the database.

public enum GenderEnum : short
 {
    Male,
    Female,
    OtherUnclear
  }

But what if I wanted to store multiple true values? For race for example somebody could be multiracial. How would I store somebody who was, say, Black and White efficiently in a database?

public enum RaceEnum : short
  {
     White,
     Black,
     Hispanic,
     Asian,
     Native,
     Unclear
  }

Solution

  • If you want an enumeration type to represent a combination of choices, define enum members for those choices such that an individual choice is a bit field. To indicate that an enumeration type declares bit fields, apply the Flags attribute to it.

    Below is a simple example.

    [Flags]
    public enum Days
    {
        None      = 0b_0000_0000,  // 0
        Monday    = 0b_0000_0001,  // 1
        Tuesday   = 0b_0000_0010,  // 2
        Wednesday = 0b_0000_0100,  // 4
        Thursday  = 0b_0000_1000,  // 8
        Friday    = 0b_0001_0000,  // 16
        Saturday  = 0b_0010_0000,  // 32
        Sunday    = 0b_0100_0000,  // 64
        Weekend   = Saturday | Sunday
    }
    
    public class FlagsEnumExample
    {
        public static void Main()
        {
            Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;
            Console.WriteLine(meetingDays);
            // Output:
            // Monday, Wednesday, Friday
    
            Days workingFromHomeDays = Days.Thursday | Days.Friday;
            Console.WriteLine($"Join a meeting by phone on {meetingDays & workingFromHomeDays}");
            // Output:
            // Join a meeting by phone on Friday
    
            bool isMeetingOnTuesday = (meetingDays & Days.Tuesday) == Days.Tuesday;
            Console.WriteLine($"Is there a meeting on Tuesday: {isMeetingOnTuesday}");
            // Output:
            // Is there a meeting on Tuesday: False
    
            var a = (Days)37;
            Console.WriteLine(a);
            // Output:
            // Monday, Wednesday, Saturday
        }
    }
    

    Reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum#enumeration-types-as-bit-flags