Converting a String to an Enumeration Value

Environment: C#

Introduction

Using enumeration types is the best way to store data such as days, months, account types, genders, and so forth.

Using this technique for data exchange, I decided to use enumerations for external representation as well. There is no problem converting an enumeration type value to a string. You only have to use the standard "ToString()" method for conversion. For example: "string x = DayOfWeek.Monday.ToString()" will place the string "Monday" in "x".

But how do you convert this string back to its internal value? First, I generated a long list of switch and case statements to handle this problem.

Using the System.Reflection class, the solution is placed in just 3–8 lines of code, and it works for any possible enumeration type.

The following example contains the method "StringToEnum" that performs the internal conversions. The other stuff is just to get a small example of how to use "StringToEnum" in your code. The example is based on the well-known enumeration type "System.DayOfWeek", but "StringToEnum" will work for any other enumeration type as well.

Source

using System;
using System.Reflection;

namespace ttype
{
  ///
  /// How to convert a string value to a given enumeration type.
  ///
  /// The static method "StringToEnum" will convert any possible
  /// string value to a given enumeration type. It's a function I
  /// never found in any framework class.
  ///
  class Class1
  {
    static void Main(string[] args)
    {
      // Check all the possible values:
      DayOut( DayOfWeek.Monday );
      DayOut( DayOfWeek.Tuesday );
      DayOut( DayOfWeek.Wednesday );
      DayOut( DayOfWeek.Thursday );
      DayOut( DayOfWeek.Friday );
      DayOut( DayOfWeek.Saturday );
      DayOut( DayOfWeek.Sunday );

      // This would throw an Exception:
      // StringToEnum( typeof(DayOfWeek), "Montag" );
    }

    static void DayOut( DayOfWeek d )
    {
      string myString = d.ToString();

      Console.WriteLine( "{0} = {1} = {2}", d, myString, (int)
                          d );

      // This line can't work because we can't convert "string"
      // to "enum type"
      // Console.WriteLine( "{0} = {1} = {2}", d, myString,
      // (DayOfWeek) myString );

      // This line will not work either:
      // DayOfWeek NewVal1 = (DayOfWeek) Convert.ChangeType
      //                     ( myString, typeof(DayOfWeek) );

      // So we have to use our "StringToEnum" Function:
      DayOfWeek NewVal = (DayOfWeek) StringToEnum
                         ( typeof(DayOfWeek), myString );
      Console.WriteLine( "{0} = {1} = {2}", d, NewVal, (int)
                                               NewVal );
    }

    ///
    /// Convert any possible string-Value of a given enumeration
    /// type to its internal representation.
    ///
    static object StringToEnum( Type t, string Value )
    {
      foreach ( FieldInfo fi in t.GetFields() )
        if ( fi.Name == Value )
          return fi.GetValue( null );    // We use null because
                                         // enumeration values
                                         // are static

      throw new Exception( string.Format("Can't convert {0} to 
                                          {1}", Value,
                                          t.ToString()) );
    }
  }
}

Downloads

Download source - 1 Kb


Comments

  • unknown

    Posted by Legacy on 01/05/2004 12:00am

    Originally posted by: eruch

    dear reader, i have a date field in an access database and i want to convert the dates in ##/##/## format into day of week, so that i can calculate the number of mondays, number of tuesdays, etc...
    
    

    should i query and say something in the design view? say what? how? please help. im lost.

    eruch

    Reply
  • Seek ye .Net

    Posted by Legacy on 03/18/2003 12:00am

    Originally posted by: Troy Kruthoff

    This article is a good example of re-creating the wheel. .Net does so much, yet it can be hard to tell what you need to create and what has been done for you. A good rule of thumb is to look at what .Net does to make serialization work. This has solved many problems for me. i.e., if .Net can serialize an enum to XML and back, then there must already exist a way to do it, outside of switch statements and for loops.
    Troy

    Reply
  • String To Enum Alternative

    Posted by Legacy on 02/22/2003 12:00am

    Originally posted by: Sean

    
    

    Example:

    enum Days { Monday, Wednesday, Friday, Sunday }

    public class Blah
    {
    public static Days getDay(string name)
    {
    Days ret;
    ret = (Days) Days.Parse(typeof(Days), name);
    return ret;
    }
    }

    Reply
  • !

    Posted by Legacy on 11/13/2002 12:00am

    Originally posted by: Goran Mitrovic

    Look at the Enum.Parse method... :)
    

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds