I wanted to design a utility class that provided some bit manipulation methods for enums with [Flags]. Ideally I wanted to embed these methods directly in the enum definition like I can do in Java, but no such luck in C#. So the helper class seemed like the next best thing.
Turns out this is pretty hard to do! You can't build a class with the constraint where T : Enum, for example. Bill Rodenbaugh comes close in his enum helper class, Enum<T>.
But when all is said and done, using the helper class doesn't really improve upon readability, efficiency, or even number of characters typed!
Here's a sample using the helper class:
public bool Enabled
{
get { return !Enum<MenuItemAttributes>.Flags.IsFlagSet(_attributes, MenuItemAttributes.Disabled); }
set { _attributes = Enum<MenuItemAttributes>.Flags.SetOrClearFlag(_attributes, MenuItemAttributes.Disabled, value); }
}
And the alternative--doing bit manipulations directly:
public bool Enabled
{
get { return (_attributes & MenuItemAttributes.Disabled) != MenuItemAttributes.Disabled; }
set { if (value) _attributes |= ~MenuItemAttributes.Disabled; else _attributes &= MenuItemAttributes.Disabled; }
}
I'm going to stick to manual bit manipulations!