Monday, December 3, 2012

Enumerations in C#

Enumerations are set of named constants. We can use them when we need to choose between set of constant values.

public enum DayType
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

Underlying type of each element is int by default but still are allowed to assign any value to the enum list.

public enum DayType
    Sunday = 0, 
    Monday = 5, 
    Tuesday = 7,
    Wednesday = 8, 
    Thursday = 10, 
    Friday = 11, 
    Saturday = 13

Get the enum string representation
string str = DayType.Monday.ToString();
Result: Monday

Get the underlying values of the item
int a = (int)DayType.Monday;
Result: 5

An example to ensure an enum value exists and then parse it.

// Fake Day of Week 
string strDOWFake = "SuperDay"; 
// Real Day of Week 
string strDOWReal = "Friday"; 
// Will hold which ever is the real DOW. 
DayType enmDOW; 
 // See if fake DOW is defined in the DayOfWeek enumeration. 
if (Enum.IsDefined(typeof(DayType), strDOWFake)) 
// This will never be reached since "SuperDay"
 // doesn't exist in the DayOfWeek enumeration. 
 enmDOW = (DayType)Enum.Parse(typeof(DayType), strDOWFake); 
 // See if real DOW is defined in the DayOfWeek enumeration. 
else if (Enum.IsDefined(typeof(DayType), strDOWReal))
 // This will parse the string into it's corresponding DOW enum object. 
 enmDOW = (DayType)Enum.Parse(typeof(DayType), strDOWReal); 
 // Can now use the DOW enum object. 
Response.Write("Today is " + enmDOW.ToString() + ".");

Today is Friday.

Print all string representations in enum list
string[] values = Enum.GetNames(typeof(DayType));
foreach (string s in values)



No comments:
Write comments
Recommended Posts × +