Last active
February 2, 2017 03:09
-
-
Save Porges/2f6de74a7d18854398bc5aa65b08e3ed to your computer and use it in GitHub Desktop.
En-flags any (sane) enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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