31

In .Net it is possible to iterate through an enumeration by using

System.Enum.GetNames(typeof(MyEnum)) 

or

System.Enum.GetValues(typeof(MyEnum))

In Silverlight 3 however, Enum.GetNames and Enum.GetValues are not defined. Does anyone know an alternative?

2
  • 9
    It's ridiculous that this isn't in the framework. Download size is no excuse to torture the devs. Dec 26, 2010 at 7:10
  • if anyone needs, specifically, GetEnumValues() and GetEnumNames(); I have implemented them (based on the answer by ptoinson and Shimmy below) as a response to the following question: stackoverflow.com/questions/7062208/… , and I think they are equivalent to the regular (but non-Silverlight) .NET functions of the same name. Aug 15, 2011 at 19:44

4 Answers 4

30

Or maybe strongly typed using linq, like this:

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

        return (
          from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
          where field.IsLiteral
          select (T)field.GetValue(null)
        ).ToArray();
    }

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

        return (
          from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
          where field.IsLiteral
          select field.Name
        ).ToArray();
    }
1
  • 1
    Better to put where T : struct,IConvertible in method definition to get closer to restrict T to enums only.
    – Kamyar
    Sep 4, 2011 at 8:19
27

I figured out how to do this without making assumptions about the enum, mimicking the functions in .Net:

public static string[] GetNames(this Enum e) {
    List<string> enumNames = new List<string>();

    foreach (FieldInfo fi in e.GetType().GetFields(BindingFlags.Static | BindingFlags.Public)){
        enumNames.Add(fi.Name);
    }

    return enumNames.ToArray<string>();
}

public static Array GetValues(this Enum e) {
    List<int> enumValues = new List<int>();

    foreach (FieldInfo fi in e.GetType().GetFields(BindingFlags.Static | BindingFlags.Public)) {
        enumValues.Add((int)Enum.Parse(e.GetType(), fi.Name, false));
    }

    return enumValues.ToArray();
}
3
  • 1
    I would however suggest that you return an IList<string> for the top method and an IList<int> for the second one. And remember that this will not support enums that represent a long value. Jun 25, 2009 at 11:53
  • 2
    You could support non-int types by getting the underlying type (Enum.GetUnderlyingType())
    – dcstraw
    Nov 11, 2010 at 22:58
  • 3
    This solution leaves a bit to be desired. The usage syntax requires you to provide an instance of the enumeration type, while the original .net methods let you work on type directly. In that respect I find the answer of @ptoinson better. Its syntax is simple and clean. GetEnumValues<MyEnumType>()
    – angularsen
    Apr 26, 2011 at 20:05
3

I haven't tried this, but the reflection APIs should work.

1

I belive this is the same as in the .NET Compact Framework. If we make the assumption that your enum values start at 0 and use every value until their range is over the following code should work.

public static IList<int> GetEnumValues(Type oEnumType)
{
  int iLoop = 0;
  bool bDefined = true;
  List<int> oList = new List<int>();

  //Loop values
  do
  {
    //Check if the value is defined
    if (Enum.IsDefined(oEnumType, iLoop))
    {
      //Add item to the value list and increment
      oList.Add(iLoop);
      ++iLoop;
    }
    else
    {
      //Set undefined
      bDefined = false;
    }
  } while (bDefined);

  //Return the list
  return oList;
}

Obviously you could tweak the code to return the enum names or to match diferent patterns e.g. bitwise values.

Here is an alternate version of the method that returns a IList<EnumType>.

public static IList<T> GetEnumValues<T>()
{
  Type oEnumType;
  int iLoop = 0;  
  bool bDefined = true;  
  List<T> oList = new List<T>();  

  //Get the enum type
  oEnumType = typeof(T);

  //Check that we have an enum
  if (oEnumType.IsEnum)
  {
    //Loop values  
    do
    {
      //Check if the value is defined    
      if (Enum.IsDefined(oEnumType, iLoop))
      {
        //Add item to the value list and increment      
        oList.Add((T) (object) iLoop);
        ++iLoop;
      }
      else
      {
        //Set undefined      
        bDefined = false;
      }
    } while (bDefined);
  }

  //Return the list  
  return oList;
}
12
  • I know you had the caveat of assuming contiguous values, but in particular any [Flags] attributed enums wouldn't work.
    – dcstraw
    Nov 11, 2010 at 22:56
  • @dcstraw - Read the last sentance, I aknowledged that you could use a different pattern to match bitwise values e.g. [Flags]; to do this ++iLoop; becomes iLoop = iLoop << 1;. Nov 12, 2010 at 8:41
  • A request if you don't mind: since this doesn't return an Array of specific enumerated types, but instead a List<int>, it doesn't actually match the behavior on the .NET platform, and caused a good bit of confusion for me when trying to determine whether this function would work for another user. Would you be open to renaming it to something else? The main issue for me was that GetArrayValues(i).ToString() returns a string of the number rather than the enum name, as is returned by the actual .NET version, although I am sure there are other possible sources of confusion. Aug 15, 2011 at 19:51
  • @shelleybutterfly - Why not use ((EnumType)GetArrayValues[i]).ToString() or in VB.NET CType(GetArrayValues(i), EnumType).ToString()? My answer states that the above code is just a simple example and can easily be re-written to return a different type or match a different enum pattern. Aug 16, 2011 at 7:32
  • Because in the questioner's case, the EnumType was not known ahead of time; only, say, Type CurrentEnumType; was the given. And I agree that you adequately clarified it in the follow-up text, it's just that it was a source of confusion for me (who was not familiar with the normal return value; an Array containing whatever the enum types are) because I had assumed that having the same name meant it returned the same thing as the standard .NET framework method. Aug 16, 2011 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.