May 26, 2008

Enumerators - the correct way to parse an enumerator.

First of all - what are enumerators?

You can think for the enumerators as for some kind of constants. They are used to check objects against.

Let's say you will have the following dropdown:



<asp:DropDownList ID="ddlGender" runat="server">

<asp:ListItem Value="1">Maleasp:ListItem>

<asp:ListItem Value="2">Femaleasp:ListItem>

<asp:ListItem Value="3">Won't shareasp:ListItem>

asp:DropDownList>



As you know the genders won't ever change, for code convenience, you may want to define an enumerator to hold them, so you can check against:



enum EnumUserGender

{

Male = 1,

Female = 2,

Unknown
= 3

}



This way, the Male element of the enumerator will have a value of 1, Female will have a value of 2 and Unknown will have a value of 3.

To check a value against enumerator you may do the following:



int Gender = 1;

if (Gender == EnumUserGender.Male)

{



}



In this case the if will evaluate to true, as the Gender variable has a value of 1.



Now, let's return to our case with the
asp:DropDownList, we want to be able to know which asp:ListItem was selected by the user. We don't want to convert the value to int first, but to receive it as a EnumUserGender variable. Let's do this in the SelectedIndex SelectedIndexChanged asp:DropDownList:



protected void ddlGender_SelectedIndexChanged(object sender, EventArgs e)

{

EnumUserGender genderSelected = (EnumUserGender)Enum.Parse(typeof(EnumUserGender), ddlGender.SelectedValue, true);

switch (genderSelected)

{

case EnumUserGender.Male:

Response.Write(
"Check our cars section!");

break;

case EnumUserGender.Female:

Response.Write(
"Check our make-up section");

break;

case EnumUserGender.Unknown:

Response.Write(
"If you want you can check either our cars section or our make-up section");

break;

default:

Response.Write(
"Sorry, there was an" +

"error, please go back and try again," +

" the error was logged and will be reviewed by our team.");

break;

}

}

}



What we did was to actually Parse the
Enum , by using its base class method Parse. It recieves 2 parameters + 1 optional:



Parameter 1 is of type
Type, this is the type to which the enumerator will be parsed / converted. In our case we use the typeof, function, passing our enum type as a paramter.

Parameter 2 is of type
string, this is the value to be parsed.

Parameter 3 is of type
bool, and indicates whether the value passed as a string should match case sensitive. If set to true, you will have insensitive Parse, so "mALe" will be parsed correctly.



1 comment:

Veselin Kolev said...

There is an interface in .NET named IEnumerator - base class for all collection iterators. In Java its equivalent is the Iterator interface. So in my opinion it is better to name your blogpost Enumerations and not Enumerators. Keep up the good work!