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!