Posted by: R Manimaran | July 8, 2008

TypeCast/Convert a String Value to Enum value in C#

TypeCast/Convert a String Value to Enum value

 

There may be a situation where we need to convert our string value to an Enumeration value. For Converting a string to Enumeration value use Enum.Parse();

 

Parse() : This method takes the following arguments

 

           Type of enumeration you want to convert

           String that you want to convert

 

Example

public enum WeekWorkingDays

        {

            Monday=1,

            Tuesday=2,

            Wednesday=3,

            Thursday=4,

            Friday=5

        }

 

//btnClick event

 

string strCurrentWorkingDay = “Wednesday”;

WeekWorkingDays CurrentDay = WeekWorkingDays.Monday;

     try

      {

        CurrentDay = (

 

WeekWorkingDays)Enum.Parse(typeof(WeekWorkingDays), strCurrentWorkingDay);

 

 

         switch(CurrentDay)

            {

              case WeekWorkingDays.Monday:

              case WeekWorkingDays.Wednesday:

                  //Project meeting will be on 9 to 10

              break;

 

              case WeekWorkingDays.Friday:

                  //Project meeting will be on 4 to 5 PM

               break;

 

              }

         }

         catch

         {

             //Invalid value

         }

Note: Enum.Parse() is a case sensiteive. Therfore if strCurrentWorkingDay value is wednesday insetead of Wednesday,

the Parse.Enum will throw an Exception.

 

To make the Enum.Parse function to accept the case insensitve data use the Overload method of Enum.Parse as follows.

 

CurrentDay = (

WeekWorkingDays)Enum.Parse(typeof(WeekWorkingDays), strCurrentWorkingDay,true);

 

 

Parameters:

          Enumeration Type

          String to be converted

          Boolean value to consider the case sensitive data

 

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

Categories

%d bloggers like this: