Sunday, March 11, 2012

Enum.GetValues does not exist on Windows Phone

Enum.GetValues does not exist on Windows Phone. The solutions here and here requires LINQ.
I've changed the solutions so they would fit Windows Phone without LINQ. I also reduced memory allocations (not using enumerators and generic collections):

public static T[] GetValues<T>()
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");

FieldInfo[] fields = enumType.GetFields();
int literalCount = 0;
for (int i = 0; i < fields.Length; i++)
if (fields[i].IsLiteral == true)
literalCount++;

T[] arr = new T[literalCount];
int pos = 0;
for (int i = 0; i < fields.Length; i++)
if (fields[i].IsLiteral == true)
{
arr[pos] = (T)fields[i].GetValue(enumType);
pos++;
}

return arr;
}

No comments: