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 msdn.com. 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<string>();
foreach (var value in allValues)
{
if (value > eVal)
{
break;
}
if ((eVal & value) != value)
{
continue;
}
strings.Add(value.ToString());
}
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");
}
usage would go like
[Flags]
public enum Testenum
{
fld1 = 1,
fld2 = 2,
fld3 = 4,
fld4 = 8,
fld5 = 16
}
#endregion
public ClassTest()
{
EnumValuesToString(Testenum.fld1 | Testenum.fld2 | Testenum.fld4);
}
may this help me/you/him or her in the future


No Comments Yet