Take this enum for example:
public enum PersonName : short
{
Mike = 1,
Robert= 2
}
I wnat to have en extension method like this:
PersonName person = PersonName.Robert; short personId = person.GetId(); //Instead of: short personId = (short)person;
Any idea how to implement this?
it need to be generic to int, short etc…, and to generic enums as well, not limited to PersonName.
This is completely impossible.
You cannot constrain a method based on an
enum‘s underlying type.Explanation:
Here is how you might try to do this:
The first constraint is unfortunately not allowed by C#, and the second constraint is not supported by the CLR.