Reputation: 14787
Consider the following enumeration:
[System.Flags]
public enum EnumType: int
{
None = 0,
Black = 2,
White = 4,
Both = Black | White,
Either = ???, // How would you do this?
}
Currently, I have written an extension method:
public static bool IsEither (this EnumType type)
{
return
(
((type & EnumType.Major) == EnumType.Major)
|| ((type & EnumType.Minor) == EnumType.Minor)
);
}
Is there a more elegant way to achieve this?
UPDATE: As evident from the answers, EnumType.Either has no place inside the enum itself.
Upvotes: 2
Views: 559
Reputation: 651
How about:
[System.Flags]
public enum EnumType: int
{
None = 0,
Black = 1,
White = 2,
Both = Black | White,
Either = None | Both
}
Upvotes: -1
Reputation: 1062550
With flags enums, an "any of" check can be generalised to (value & mask) != 0
, so this is:
public static bool IsEither (this EnumType type)
{
return (type & EnumType.Both) != 0;
}
assuming you fix the fact that:
Both = Black | White
(as Black & White
is an error, this is zero)
For completeness, an "all of" check can be generalised to (value & mask) == mask
.
Upvotes: 9
Reputation: 61589
Why not simply:
public enum EnumType
{
// Stuff
Either = Black | White
}
Upvotes: 1