#459 – Assigning a Value of a Different Type to an enum

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;

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: