#459 – Assigning a Value of a Different Type to an enum
November 21, 2011 Leave a comment
You can convert to an enum value from its underlying type by casting the underlying type (e.g. int) to the enum type. You can also assign a value of a different type, one that does not match the underlying type, as long as the cast succeeds.
// By default stored as int, with values 0,1,2,3
public enum Mood { Crabby, Happy, Petulant, Elated };
static void Main()
{
byte moodValue = 3;
Mood mood;
// Works (byte -> int)
mood = (Mood)moodValue;
// Also works, since cast converts value to 2 (Petulant)
double moodValue2 = 2.1;
mood = (Mood)moodValue2;
}