#1,059 – Converting from Numeric to Enumerated Types

You can convert from a numeric type to an enumerated type using the cast operator.  For example, to convert from numeric constants to an enum, we can do the following:

        public enum Weekday
            Sunday = 1,
            Monday,     // 2
            Tuesday,    // 3, etc.

        static void Main(string[] args)
            Weekday day = (Weekday)5;  // Thursday
            Console.WriteLine(day.ToString());  // "Thursday"

            Weekday day2 = (Weekday)8;    // Works!
            Console.WriteLine(day2.ToString());  // Just "8"

Notice that the cast works even if there is not a defined enumerated value that matches the specified type. We can store a value of 8 in a Weekday type even though we didn’t define a Weekday with a value of 8.