I have the following enum
[Flags]
public enum WeekDays
{
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32,
Sunday = 64
}
In the UI, user can select ceratain days: Monday, Tuesday, Wednesday for example. The user selection of Monday, Tuesday, Wednesday is 7. This values is saved in the databse in a column called Days.
Now if I have a class:
public class Week
{
public bool Monday { get; set; }
public bool Tuesday { get; set; }
public bool Wednesday { get; set; }
public bool Thursday { get; set; }
public bool Friday { get; set; }
public bool Saturday { get; set; }
public bool Sunday { get; set; }
}
How can I bind that value 7 and make the appropriate properties true or false. Example: 7 is equivalent for Monday, Tuesday, Wednesday enum. If I convert the value 7 to my class Week, the result will be properties: Monday, Tuesday, Wednesday are true, and the rest false.
If instead I have a class week where properties: Monday, Tuesday, Wednesday are true, and convert that into an enum WeekDays the result will be 7.
How can I do that?
You could make the Week
have a property or field of type WeekDays
that keeps track of which flags are active. And then all your boolean properties just check against that enum value, and on set update it correctly. This allows you to do this:
Week w = new Week();
w.Monday = true;
Console.WriteLine(w.Days); // Monday
w.Tuesday = true;
w.Wednesday = true;
Console.WriteLine(w.Days); // Monday, Tuesday, Wednesday
See the Week
code is below, which is quite verbose (albeit introducing a SetDaysFlag
helper method):
public class Week
{
public WeekDays Days
{ get; set; }
public bool Monday
{
get { return (Days & WeekDays.Monday) != 0; }
set { SetDaysFlag(WeekDays.Monday, value); }
}
public bool Tuesday
{
get { return (Days & WeekDays.Tuesday) != 0; }
set { SetDaysFlag(WeekDays.Tuesday, value); }
}
public bool Wednesday
{
get { return (Days & WeekDays.Wednesday) != 0; }
set { SetDaysFlag(WeekDays.Wednesday, value); }
}
public bool Thursday
{
get { return (Days & WeekDays.Thursday) != 0; }
set { SetDaysFlag(WeekDays.Thursday, value); }
}
public bool Friday
{
get { return (Days & WeekDays.Friday) != 0; }
set { SetDaysFlag(WeekDays.Friday, value); }
}
public bool Saturday
{
get { return (Days & WeekDays.Saturday) != 0; }
set { SetDaysFlag(WeekDays.Saturday, value); }
}
public bool Sunday
{
get { return (Days & WeekDays.Sunday) != 0; }
set { SetDaysFlag(WeekDays.Sunday, value); }
}
/// <summary>
/// Set or unset the flag on the <c>Days</c> property.
/// </summary>
/// <param name="flag">The flag to set or unset.</param>
/// <param name="state">True when the flag should be set, or false when it should be removed.</param>
private void SetDaysFlag (WeekDays flag, bool state)
{
if (state)
Days |= flag;
else
Days &= ~flag;
}
}