March 19, 2009

Enum.GetValues on .net compact framework

Filed under: Uncategorized — Tags: , , — yasi8h @ 8:25 am

i recently needed to use Enum.GetValues on a .netcf project. but unfortunately it is not there in .netcf. googling gives a lot of solutions that we can use in .netcf. but i couldn’t find one that worked exactly as Enum.GetValue did.

Retrieves an array of the values of the constants in a specified enumeration.

is the method description for the Enum.GetValue, taken from most of the solutions online returned only an array of the constants. not their values. so i came up with the following. now of course this is inspired from lot of smart people’s code that i took from around the net sometime back. 😉

private static string EnumValuesToString(object e)
var eVal = (int) e;
var allValues = GetValues(typeof (Testnum));
var strings = new List();

foreach (var value in allValues)
if (value > eVal)
if ((eVal & value) != value)

return string.Join(“,”, strings.ToArray());

private static int[] GetValues(Type enumType)
if (enumType.BaseType ==
typeof (Enum))
//get the public static fields (members of the enum)
var fi = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
//create a new enum array
var values = new int[fi.Length];
//populate with the values
for (var iEnum = 0; iEnum < fi.Length; iEnum++) { values[iEnum] = (int) fi[iEnum].GetValue(null); } //return the array return values; } //the type supplied does not derive from enum throw new ArgumentException("enumType parameter is not a System.Enum"); } [/sourcecode] usage would go like [sourcecode language='csharp'] [Flags] public enum Testenum { fld1 = 1, fld2 = 2, fld3 = 4, fld4 = 8, fld5 = 16 } #endregion public ClassTest() { EnumValuesToString(Testenum.fld1 | Testenum.fld2 | Testenum.fld4); } [/sourcecode] may this help me/you/him or her in the future 🙂


Create a free website or blog at