Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through an enumeration in Silverlight?

Tags:

silverlight

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?

like image 311
eriksmith200 Avatar asked Jun 24 '09 13:06

eriksmith200


People also ask

How do you iterate through an enumeration?

To iterate through an enumeration, you can move it into an array using the GetValues method. You could also iterate through an enumeration using a For... Each statement, using the GetNames or GetValues method to extract the string or numeric value.

Does enum GetValues use reflection?

Roughly, yes. There are two kind of reflection code, the general kind that goes through RuntimeType and the specific kind that uses dedicated CLR helper functions. The latter uses type info that can retrieved from the internal type representation that the CLR maintains. The fast kind.


1 Answers

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();     } 
like image 147
ptoinson Avatar answered Oct 25 '22 05:10

ptoinson