#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.
            Wednesday,
            Thursday,
            Friday,
            Saturday
        };

        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.

1059-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,059 – Converting from Numeric to Enumerated Types

  1. Pingback: Dew Drop – March 24, 2014 (#1749) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: