Mobile Zone is brought to you in partnership with:

My name is Toni Petrina and I am a software developer and an occasional speaker. Although I primarily develop on the Microsoft stack, I like to learn new technologies. My hobbyist projects range from game development, regardless of the technology, to ALM. I spend most of my time with my girlfriend and someday I will learn how to play the guitar properly. Toni is a DZone MVB and is not an employee of DZone and has posted 69 posts at DZone. You can read more from them at their website. View Full User Profile

Enum.GetValues for Windows Phone (and Portable Libraries)

03.17.2013
| 2316 views |
  • submit to reddit

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 Toni Petrina, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)