Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining an extension method for Enum in Silverlight

Tags:

c#

silverlight

Silverlight is missing the GetValues for enums, so i thought i would write an extension method to cover my needs in my project. Only thing is, Im not sure what the signature of the extension method should look like. Im thinking something along the lines of:

public static IEnumerable<Enum> GetValues(this Enum e)

But its not showing up in intellisense, so i know im wrong. Any pointers?

like image 842
Mike_G Avatar asked Dec 14 '25 12:12

Mike_G


1 Answers

I think i figured it out by combining a little reflection with and digging in Reflector:

public static Array GetValues(this Enum enumType)
   {
       Type type = enumType.GetType();

       FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);

       Array array = Array.CreateInstance(type, fields.Length);

       for (int i = 0; i < fields.Length; i++)
       {
           var obj = fields[i].GetValue(null);
           array.SetValue(obj, i);
       }

       return array;
   }
like image 173
Mike_G Avatar answered Dec 16 '25 02:12

Mike_G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!