It's very useful to take an enum and bind it into bind-able controls (like drop down list, check box, grid view and etc). For example, if we have an enum which represents bug statuses and you want to bind it into a drop down list.
public enum Bug
{
Opened = 1,
Closed = 2,
Rejected = 3,
Resolved = 4,
InProgress = 5
}
In addition, usually in a UI we want to separate between the enum words (for example to change the "InProgress" to "In Progress").
I search over the net and I found some solution but in all of them I needed to extend my current enum (like using attribute in this solution), so I decided to implement one of myself:
public static class EnumHelper
{
public static IDictionary<string, int> GetList<TEnum>()
{
return GetList<TEnum>(false);
}
public static IDictionary<string, int> GetList<TEnum>(bool splitString)
{
Type type = typeof(TEnum);
Dictionary<string, int> list = new Dictionary<string, int>();
Array enumValues = Enum.GetValues(type);
foreach (Enum value in enumValues)
{
int enumValue = Convert.ToInt32(((TEnum)Enum.Parse(type, value.ToString())));
string sb = (splitString) ? SplitString(value) : value.ToString();
list.Add(sb, enumValue);
}
return list;
}
private static string SplitString(Enum value)
{
StringBuilder sb = new StringBuilder();
char[] chars = value.ToString().ToCharArray();
sb.Append(chars[0]);
for (int i = 1; i < chars.Length - 1; i++)
{
if ((chars[i].ToString() == chars[i].ToString().ToUpper())
&& (chars[i - 1].ToString() != chars[i - 1].ToString().ToUpper()))
{
sb.Append(" ");
}
sb.Append(chars[i]);
}
sb.Append(chars[chars.Length - 1]);
return sb.ToString();
}
}
How do we use this code?
In case we just want to bind it without separate between the enum words, it will be like this:
var bugs = EnumHelper.GetList<Bug>();
And in case we want to separate between the words will have something like that:
var bugs = EnumHelper.GetList<Bug>(true);
Challenge:
How do you synchronies between enum (which execute in web/service context) and a table/database context?
For example you have this bug statuses enum and in addition you have a bug table with numeric status column. The status column values are the same enum numeric values. After deployment, in order to understand this column value you must look at the enum that represent it. But in order to do so, you must open your code…