Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum with flags attribute

Tags:

c#

.net

I have the enum:

    [Flags, Serializable,]
    public enum WeekDays {
        Sunday = 1,
        Monday = 2,
        Tuesday = 4,
        Wednesday = 8,
        Thursday = 16,
        Friday = 32,
        Saturday = 64,
        WeekendDays = Sunday | Saturday,
        WorkDays = Monday | Tuesday | Wednesday | Thursday | Friday,
        EveryDay = WeekendDays | WorkDays
    }

And, I have property WeekDays in a class that contain value of WeekDays enum:

public int WeekDays {get; set;}

For example WorkDays contain 62( from Monday to Friday).
How to check that current WeekDays property contain current day?

like image 598
user348173 Avatar asked Nov 28 '22 17:11

user348173


2 Answers

Enum has method HasFlag to determine whether one or more bit fields are set in the current instance.

like image 144
Kirill Polishchuk Avatar answered Dec 05 '22 17:12

Kirill Polishchuk


Use the bitwise operator & to see if a value is part of a set:

var today = WeekDays.Thursday;
var workdays = WeekDays.WorkDays;

if((today & workdays) == today) {
    // today is a workday
}

if((today & WeekDays.Friday) == today) {
    // it's friday
}
like image 32
Jon Avatar answered Dec 05 '22 17:12

Jon