Skip to content

Instantly share code, notes, and snippets.

@coldacid
Created January 3, 2013 07:19
Show Gist options
  • Save coldacid/4441484 to your computer and use it in GitHub Desktop.
Save coldacid/4441484 to your computer and use it in GitHub Desktop.
GetNames and GetValues for enums in Silverlight. Includes cache of results to avoid wasting time in reflection later on.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Charabaruk.Utility
{
static class EnumEx
{
private static Dictionary<Type, Tuple<string[], Array>> cache = new Dictionary<Type,Tuple<string[],Array>>();
private static void GuardAndGenerate(Type enumType)
{
if (!enumType.IsEnum)
throw new ArgumentException(string.Format("Type '{0}' is not an enum", enumType.Name));
if (!cache.ContainsKey(enumType))
{
string[] names;
Array values;
GetEnumData(enumType, out names, out values);
cache[enumType] = Tuple.Create(names, values);
}
}
public static string[] GetNames(Type enumType)
{
GuardAndGenerate(enumType);
return cache[enumType].Item1;
}
public static Array GetValues(Type enumType)
{
GuardAndGenerate(enumType);
return cache[enumType].Item2;
}
private static void GetEnumData(Type enumType, out string[] enumNames, out Array enumValues)
{
var fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
string[] names = new string[fields.Length];
Array values = Array.CreateInstance(enumType, fields.Length);
for (int i = 0; i < fields.Length; i++)
{
values.SetValue(Enum.ToObject(enumType, fields[i].GetValue(null)), i);
names.SetValue(Enum.GetName(enumType, fields[i].GetValue(null)), i);
}
enumNames = names;
enumValues = values;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment