UPDATE: Microsoft will be offering a substitute for this method in .NET Framework 4, so you could say that this post is obsolete.
I was working with Windows ACL permissions and I was attempting to find out whether a user had Read permissions to a file. Permissions are represented in the form of an enum to something of this effect:
To further complicate things, Windows permissions are represented under 2 different enum classes, System.IO.FileAccess and System.Security.AccessControl.FileSystemRights. So, in order to persist these permissions to the database, I chose to also persist the respective enum class in the form of text, and then pull it back out of the database and perform Enum.Parse() on the text.
Whenever a file had Modify permissions, there was no concise way of determining that this also implied the Read permission because I was dealing with the generic Enum class. As you can see, when you attempt bitwise operations on the Enum class, this is what you get:
Error: Operator '&' cannot be applied to operands of type 'System.Enum' and 'System.Enum'
So, in order to get around this, I chose to cast the Enums to a type that I could use bitwise operations on, which lead me to generate this function:
public static bool EnumIsCompositeOf(Enum little, Enum big) { if (!Type.Equals(little.GetType(), big.GetType())) throw new ArgumentException("Enums must be of the same type."); ulong littleVal; ulong bigVal; TypeCode typeCode = little.GetTypeCode(); switch (typeCode) { case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: littleVal = ulong.Parse(little.ToString("D")); bigVal = ulong.Parse(big.ToString("D")); break; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: littleVal = (ulong)long.Parse(little.ToString("D")); bigVal = (ulong)long.Parse(big.ToString("D")); break; default: throw new ArgumentException("Enums are derived from an unknown type."); } ulong intersection = littleVal & bigVal; return intersection == littleVal ? true : false; }
