• Register

Solution:

In case you want an enumeration type to represent a combination of options, identify enum members for those options such that an distinct choice is a bit field. For indicating that an enumeration type declares bit fields, executes the Flags attribute to it.

Follw the below code:

[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
    }
}

 Or,

You can apply the flags attribute that approves bitwise mixing with the logic OR operator and place each values a multiple of 2 employing the sequence of binary values from 0:

[Flags]
public enum RaceEnum : short
{
   White = 0,
   Black = 1,
   Hispanic = 2,
   Asian = 4,
   Native = 8,
   Unclear = 16
}

You can check in case a variable has a flag set employing the Enum.HasFlag method.

For Example:

var somehuman = RaceEnum.Black | RaceEnum.Hispanic;

if ( somehuman.HasFlag(RaceEnum.Asian) ) ...

 

posted Jul 4 in c# 17,260 points