Well, its sort of possible, but on the flip side you will have to specify what the underlying type is:
public static T GetId<T>(this Enum value)
where T : struct, IComparable, IFormattable, IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
since System.Enum
is the base class of all enum types. Call it:
PersonName person = PersonName.Robert;
short personId = person.GetId<short>();
Since you can cast almost anything to long
, you could even have this:
public static long GetId(this Enum value)
{
return Convert.ToInt64(value);
}
and call:
PersonName person = PersonName.Robert;
long personId = person.GetId();
What is otherwise possible is to get an object
instance returned, like this or so:
public static object GetId(this Enum value)
{
return Convert.ChangeType(task, Enum.GetUnderlyingType(value.GetType()));
}
PersonName person = PersonName.Robert;
var personId = (short)person.GetId();
// but that sort of defeats the purpose isnt it?
All of which involves some sort of boxing and unboxing. The second approach looks better (you could even make it int
, the standard type) and then the first.