Over a million developers have joined DZone.

Enum.GetValues for Windows Phone (and Portable Libraries)

DZone 's Guide to

Enum.GetValues for Windows Phone (and Portable Libraries)

· Mobile Zone ·
Free Resource

Windows Phone is missing quite a lot of different things, but I never figured it would be missing something as basic as Enum.GetValues. Since I need it (obviously for my current top secret project), I just went ahead and wrote a replacement. Also, since the original returned Array, I figured that the new and improved method should be much better and that it should return IEnumerable where T should be the enumeration type. It makes code a lot prettier.

So, without further ado, here is the final code:

public static IEnumerable<T> GetValues<T>()
    if (!typeof(T).IsEnum)
        throw new InvalidOperationException("Type must be enumeration type.");

    return GetValues_impl<T>();

private static IEnumerable<T> GetValues_impl<T>()
    return from field in typeof(T).GetFields()
            where field.IsLiteral && !string.IsNullOrEmpty(field.Name)
            select (T)field.GetValue(null);

It couldn’t be implemented as an extension method since you cannot define extension methods on a type. You have full freedom to implement this method in e.g. EnumHelpers class. I am also aware that this method has no caching whatsoever implemented and that you will need to do that in case you are using it in highly performant code, but this will suffice for basic daily needs.

Happy coding.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}