Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum from string, int, etc

Using extension method we can create methods to convert an enum to other datatype like string, int by creating extension methods ToInt(), ToString(), etc for the enum.

I wonder how to implement the other way around, e.g. FromInt(int), FromString(string), etc. As far as I know I can't create MyEnum.FromInt() (static) extension method. So what are the possible approaches for this?

like image 982
Louis Rhys Avatar asked Jan 18 '11 08:01

Louis Rhys


1 Answers

I would avoid polluting int or string with extension methods for enums, instead a good old fashioned static helper class might be in order.

public static class EnumHelper {    public static T FromInt<T>(int value)    {        return (T)value;    }    public static T FromString<T>(string value)   {      return (T) Enum.Parse(typeof(T),value);   } } 
like image 84
Jamiec Avatar answered Sep 22 '22 01:09

Jamiec