using System; namespace FirstGearGames.Utilities.Maths { public static class Enums { /// /// Determine an enum value from a given string. This can be an expensive function. /// /// /// Text of string. /// Default value if enum couldn't be found. /// Enum found or default value if no enum is found. public static T FromString(string text, T defaultValue) { //If string is empty or null return default value. if (string.IsNullOrEmpty(text)) return defaultValue; //If enum isn't defined return default value. if (!Enum.IsDefined(typeof(T), (string)text)) return defaultValue; //Return parsed value. return (T)Enum.Parse(typeof(T), text, true); } /// /// Returns if whole(extended enum) has any of the part values. /// /// /// Values to check for within whole. /// Returns true part is within whole. public static bool Contains(this Enum whole, Enum part) { //If not the same type of Enum return false. /* Commented out for performance. Designer * should know better than to compare two different * enums. */ //if (!SameType(value, target)) // return false; /* Convert enum values to ulong. With so few * values a uint would be safe, but should * the options expand ulong is safer. */ ulong wholeNum = Convert.ToUInt64(whole); ulong partNum = Convert.ToUInt64(part); return ((wholeNum & partNum) != 0); } /// /// Returns if part values contains any of whole(extended enum). /// /// /// /// Returns true whole is within part. public static bool ReverseContains(this Enum whole, Enum part) { //If not the same type of Enum return false. /* Commented out for performance. Designer * should know better than to compare two different * enums. */ //if (!SameType(value, target)) // return false; /* Convert enum values to ulong. With so few * values a uint would be safe, but should * the options expand ulong is safer. */ ulong wholeNum = Convert.ToUInt64(whole); ulong partNum = Convert.ToUInt64(part); return ((partNum & wholeNum) != 0); } /// /// Returns if an enum equals a specified value. /// /// /// /// public static bool Equals(this Enum value, Enum target) { //If not the same type of Enum return false. /* Commented out for performance. Designer * should know better than to compare two different * enums. */ //if (!SameType(value, target)) // return false; ulong valueNum = Convert.ToUInt64(value); ulong wholeNum = Convert.ToUInt64(target); return (valueNum == wholeNum); } /// /// Returns if a is the same Enum as b. /// /// /// /// public static bool SameType(Enum a, Enum b) { return (a.GetType() == b.GetType()); } } }