Question

In .Net 4.0, I use System.Enum.GetValues(typeof(Gender)) to get the list of enum item.
In a complete example, I use to look for enum value in this way:

    Gender retVal = Gender.Male;

    foreach (Gender enumType in System.Enum.GetValues(typeof(Gender)))
    {
        if (enumType.ToString().Trim().ToUpper().Substring(0,1).Equals(stringToEnum.Trim().ToUpper()))
        {
            retVal = enumType;
            break;
        }
    }  

But how could I do this in .Net 3.5 (Pocket PC) ?
Thanks in advance !

I use the answers below but It doesn't work for me. Here's the code:

Enum Values:

namespace Ionic.Zlib
{
    public enum CompressionLevel
    {
        Level0 = 0,
        None = 0,
        Level1 = 1,
        BestSpeed = 1,
        Level2 = 2,
        Level3 = 3,
        Level4 = 4,
        Level5 = 5,
        Level6 = 6,
        Default = 6,
        Level7 = 7,
        Level8 = 8,
        BestCompression = 9,
        Level9 = 9,
    }
}  

Usage:

I just miss to initialize new object. This works now:

public static Ionic.Zlib.CompressionLevel GetCompressionLevel(string Expression)
{
    Ionic.Zlib.CompressionLevel result = Ionic.Zlib.CompressionLevel.None;
    foreach (Ionic.Zlib.CompressionLevel item in EnumGetValues(new Ionic.Zlib.CompressionLevel()))
    {
        if(object.Equals(item.ToString().Trim().ToUpper(), Expression.Trim().ToUpper()))
        {
            result = item;
            break;
        }
    }
    return result;
}
Was it helpful?

Solution

There's a blog post here (archived here) which achieves it via reflection:

public IEnumerable<Enum> GetValues(Enum enumeration)
{
    List<Enum> enumerations = new List<Enum>();
    foreach (FieldInfo fieldInfo in enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
    {
        enumerations.Add((Enum)fieldInfo.GetValue(enumeration));
    }
    return enumerations;
}

OTHER TIPS

System.Enum.GetValues is not supported on .NET CF 3.5, you should find another way to iterate on your enum, for example have a look here:

http://social.msdn.microsoft.com/forums/en-US/netfxcompact/thread/dbb6c1ff-935a-4fba-84a2-4cb6e892a61f/

In addition to shamp00's answer I would suggest to create a static method with a generic type parameter. That way you don't need to pass a variable of the enum type to the method:

public static class EnumHelper
{
    public static TEnum[] GetValues<TEnum>()
    {
        return typeof(TEnum)
            .GetFields(BindingFlags.Static | BindingFlags.Public)
            .Select(fieldInfo => (TEnum)fieldInfo.GetValue(null))
            .ToArray();
    }
}

Usually I don't like class ending on "Helper", but using just Enum would conflict with the built-in Enum-class.

To use this method just invoke it with your enum type:

var values = EnumHelper.GetValues<MyEnum>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top