// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; namespace E { public static class FlagHack { public static bool IsFlagDefined(this Enum en) { int allbits = 0; foreach(int bit in Enum.GetValues(en.GetType())) { allbits |= bit; } int val = Convert.ToInt32(en); return (val & allbits) == val; } private static Dictionary cache = new Dictionary(); public static bool IsFlagDefinedCached(this Enum en) { Type t = en.GetType(); int allbits; if(cache.ContainsKey(t)) { allbits = cache[t]; } else { allbits = 0; foreach(int bit in Enum.GetValues(t)) { allbits |= bit; } cache.Add(t, allbits); } int val = Convert.ToInt32(en); return (val & allbits) == val; } } [Flags] public enum X { X1=1, X2=2, X3=4 }; public class Program { public const int N = 1000000; public static void Main(string[] args) { X ox = X.X1 | X.X3; DateTime dt1 = DateTime.Now; for(int i = 0; i < N; i++) { if(!ox.IsFlagDefined()) { throw new Exception("Ooops"); } } DateTime dt2 = DateTime.Now; Console.WriteLine((dt2 - dt1).TotalSeconds); DateTime dt3 = DateTime.Now; for(int i = 0; i < N; i++) { if(!ox.IsFlagDefinedCached()) { throw new Exception("Ooops"); } } DateTime dt4 = DateTime.Now; Console.WriteLine((dt4 - dt3).TotalSeconds); } } }