Thanks to this question I managed to work out how to constrain my generic method to accept only enums.
Now I'm trying to create a generic method so that I can bind a drop-down to any enum I choose, displaying the description in the drop-down, with the value equal to the numeric value of the enum value.
public static object EnumToDataSource<T>() where T : struct, IConvertible {
if (!typeof(T).IsEnum) // just to be safe
throw new Exception(string.Format("Type {0} is not an enumeration.", typeof(T)));
var q = Enum.GetValues(typeof(T)).Cast<T>()
.Select(x => new { ID = DataUtil.ToByte(x), Description = x.ToString() }) // ToByte() is my own method for safely converting a value without throwing exceptions
.OrderBy(x => x.Description);
return q;
}
Looks nice, but ToByte() always returns 0, even if my enumeration has values explicitly set, like so:
public enum TStatus : byte {
Active = 1,
Inactive = 0,
}
Outside the generic method, if I cast a value of type TStatus
to byte
, it works perfectly. Inside the generic method, if I try cast something of type T
to byte
I get a compiler error.
I can't find anything in the Enum static interface to do this, either.
So, how do I get the numeric value of the enum inside the generic? (I'll also accept any other advice about optimizing my code gratefully...)
Edit: Um, er... turns out that the thing wasn't working... because there was a bug in my ToByte() method... (blush). Oh well, thanks anyway - I learned a lot from this!
I think the simplest thing to do is use the Convert class instead of a cast:
T someValueThatIsAnEnum;
byte enumValue = Convert.ToByte( (object)someValueThatIsAnEnum );
Alternatively, you can rely on the fact that enums can convert themselves to a string representation, and parse themselves back as well:
T someValueThatIsAnEnum;
string enumAsString = someValueThatIsAnEnum.ToString();
byte enunValue = (byte)Enum.Parse( typeof(T), enumAsString );
You can do it like this (change DataUtil.ToByte(x) to x.ToByte(null)):
public static object EnumToDataSource<T>() where T : struct, IConvertible
{
if (!typeof (T).IsEnum) throw new Exception(string.Format("Type {0} is not an enumeration.", typeof (T)));
var q =
Enum.GetValues(typeof (T)).Cast<T>().Select(x => new {ID = x.ToByte(null), Description = x.ToString()}).OrderBy(
x => x.Description).ToArray();
return q;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With