Using extension method we can create methods to convert an enum to other datatype like string, int by creating extension methods ToInt()
, ToString()
Another approach (for the string part of your question):
///
/// Static class for generic parsing of string to enum
///
/// Type of the enum to be parsed to
public static class Enum
{
///
/// Parses the specified value from string to the given Enum type.
///
/// The value.
///
public static T Parse(string value)
{
//Null check
if(value == null) throw new ArgumentNullException("value");
//Empty string check
value = value.Trim();
if(value.Length == 0) throw new ArgumentException("Must specify valid information for parsing in the string", "value");
//Not enum check
Type t = typeof(T);
if(!t.IsEnum) throw new ArgumentException("Type provided must be an Enum", "T");
return (T)Enum.Parse(typeof(T), value);
}
}
(Partially inspired by: http://devlicious.com/blogs/christopher_bennage/archive/2007/09/13/my-new-little-friend-enum-lt-t-gt.aspx)