Master c# enum with System.Enum.Parse

[This post has been updated! please go to the end of it to check the update]

We start with a typical enum in C#:

public enum WEEK_DAY : byte
{
 MONDAY    = 0x01,
 TUESDAY   = 0x02,
 WEDNESDAY = 0x03,
 THURSDAY  = 0x04,
 FRIDAY    = 0x05,
 SATURDAY  = 0x06,
 SUNDAY    = 0x07
}

With System.Enum.Parse you can do the following:

/*
 * Converting a numeric value to an enum name
 */
byte numericValue = 0x04;
WEEK_DAY dayOfTheWeek = (WEEK_DAY)
							(
								System.Enum.Parse
								(
								typeof(WEEK_DAY),
								numericValue.ToString()
								)
							);

/*
 * Freindly printing of enum names
 */
// this will print "THURSDAY"
Console.WriteLine(dayOfTheWeek.ToString());

Update:I found today in this post a simpler way to format and print out an enumeration entry:

            Console.WriteLine(WEEK_DAY.FRIDAY.ToString("G")); // Friday  (String)
            Console.WriteLine(WEEK_DAY.FRIDAY.ToString("F")); // Friday  (String)
            Console.WriteLine(WEEK_DAY.FRIDAY.ToString("X")); // 05      (Hex)
            Console.WriteLine(WEEK_DAY.FRIDAY.ToString("D")); // 5       (Decimal)
I found it in this
Advertisements

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: