Am I fundamentally misunderstanding how HasFlags works? I cannot understand why this code is failing.
This code takes a value and determines if it is a valid combination of values of my Enum.
Two sub groups of Enum values are identified by ORing other members: JustTheMonths and Exclusives. JustTheMonths is declared in the Enum, and Exclusives is built in the validation method.
When I pass 1 or 2 (Unassigned or Unknown) to this method, it correctly identifies them as valid - Exclusives, but not members of JustTheMonths.
But when I pass 4 to this code, it correctly identifies it as a member of the whole set, but incorrectly identifies it as a member of sub-group JustTheMonths.
What am I doing wrong here? Why does my code think that 4 is a member of (8 | 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096 | 8172 | 16344) ?
private void Form1_Load(object sender, EventArgs e)
{
FloweringMonth test = FloweringMonth.NotApplicable;
if (IsValidFloweringMonthValue((int)test))
{
System.Diagnostics.Debug.WriteLine("Valid");
}
else
{
System.Diagnostics.Debug.WriteLine("Not Valid");
}
}
[Flags]
public enum FloweringMonth
{
Unassigned = 1, Unknown = 2, NotApplicable = 4,
Jan = 8, Feb = 16, Mar = 32, Apr = 64, May = 128, Jun = 256,
Jul = 512, Aug = 1024, Sep = 2048, Oct = 4086, Nov = 8172, Dec = 16344,
JustMonths = (Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec)
}
public static bool IsValidFloweringMonthValue(int value)
{
FloweringMonth incoming = (FloweringMonth)value;
FloweringMonth AllVals = FloweringMonth.Unassigned | FloweringMonth.Unknown |
FloweringMonth.NotApplicable | FloweringMonth.Jan | FloweringMonth.Feb |
FloweringMonth.Mar | FloweringMonth.Apr | FloweringMonth.May |
FloweringMonth.Jun | FloweringMonth.Jul | FloweringMonth.Aug |
FloweringMonth.Sep | FloweringMonth.Oct | FloweringMonth.Nov | FloweringMonth.Dec;
// does the incoming value contain any enum values from AllVals?
bool HasMembersOfAll = AllVals.HasFlag(incoming);
if (!HasMembersOfAll) return false;
// does the incoming value contain any enum values from JustTheMonths?
bool HasMembersOfMonths = FloweringMonth.JustMonths.HasFlag(incoming);
// does it contain any enum values from the set of three exclusive values?
FloweringMonth Exclusives = (FloweringMonth.Unassigned |
FloweringMonth.Unknown | FloweringMonth.NotApplicable);
bool HasMembersOfExclusives = Exclusives.HasFlag(incoming);
// an exclusive value cannot be mixed with any month values
if (HasMembersOfMonths && HasMembersOfExclusives) return false; // bad combo
// an exclusive value cannot be mixed with other exclusive values
if (incoming.HasFlag(FloweringMonth.Unassigned) &&
incoming.HasFlag(FloweringMonth.Unknown)) return false;
if (incoming.HasFlag(FloweringMonth.Unassigned) &&
incoming.HasFlag(FloweringMonth.NotApplicable)) return false;
if (incoming.HasFlag(FloweringMonth.Unknown) &&
incoming.HasFlag(FloweringMonth.NotApplicable)) return false;
return true;
}