Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active February 2, 2017 03:09
Show Gist options
  • Save Porges/2f6de74a7d18854398bc5aa65b08e3ed to your computer and use it in GitHub Desktop.
Save Porges/2f6de74a7d18854398bc5aa65b08e3ed to your computer and use it in GitHub Desktop.
En-flags any (sane) enum
void Main()
{
Flags<Color> colors = new Flags<Color>();
Console.WriteLine(colors);
colors.Set(Color.Red);
Console.WriteLine(colors);
colors.Set(Color.White);
Console.WriteLine(colors);
}
enum Color { Red, Black, White };
struct Flags<T>
{
ulong value;
private ulong Repr(T flag) => 1UL << Convert.ToInt32(flag);
public void Set(T flag) => value |= Repr(flag);
public void Clear(T flag) => value &= ~(Repr(flag));
public bool Has(T flag) => (value & Repr(flag)) != 0;
public override string ToString()
{
var me = this;
return string.Join(", ", Enum.GetValues(typeof(T)).Cast<T>().Where(me.Has));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment