// // Sample code for book "C# in Front Office" (ISBN/EAN13: 144215358X / 9781442153585) // // Code is provided as it is and without any guarentee. Using this code for both // personal and commercial purpose is permitted if the original source of this // code is included. // // Author email: greenwich2greenwich@gmail.com // Book website: http://book.greenwich2greenwich.com/CsInFrontOffice/ // Code Example: http://book.greenwich2greenwich.com/Examples/ // using System; using System.Reflection; /// /// Enum related utility methods. Its beauty is intuitive user interface. /// /// By comparison, in C++, usually a lengthy if-elif-elif-...-else or a switch-case structure is required. /// Even though such code can be wrapped into a macro or a a fancy template class,such approach is not very /// natural. Also it typically will require some additional efforts when defining an enum. /// /// See section 7.8 in the book. /// class MyEnumUtil { #region String2Enum /// /// Converts a string to an Enum. /// /// If you are using VS2003 which does not support generics, see the next method. /// /// Enum type /// a String /// An Enum value, throw if failed public static Type_ String2Enum(String value_) { foreach (FieldInfo fi in typeof(Type_).GetFields()) { if (fi.Name == value_) { return (Type_)fi.GetValue(null); } } throw new Exception(string.Format("Can't convert {0} to {1}", value_, typeof(Type_))); } /// /// Converts a String to Enum (VS2003 version). The previous method is preferred if you are using higher version. /// /// /// /// public static object String2Enum(Type type_, String value_) { foreach (FieldInfo fi in type_.GetFields()) { if (fi.Name == value_) { return fi.GetValue(null); } } throw new Exception(string.Format("Can't convert {0} to {1}", value_, type_.GetType())); } #endregion } class Test { enum CityEnum { NYC, LDN, SHA }; static void Main(string[] args) { CityEnum city1 = MyEnumUtil.String2Enum("SHA"); // VS2005/2008 version CityEnum city2 = (CityEnum)MyEnumUtil.String2Enum(typeof(CityEnum), "NYC"); // VS2003 version Console.WriteLine(String.Format("city1 = {0}", city1.ToString())); // also serve as an example of coverting Console.WriteLine(String.Format("city2 = {0}", city2.ToString())); // Enum to string } }