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 […]
CodeGuru content and product recommendations are
editorially independent. We may make money when you click on links
to our partners.
Learn More
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
{
class Class1
{
static void Main(string[] args)
{
DayOut( DayOfWeek.Monday );
DayOut( DayOfWeek.Tuesday );
DayOut( DayOfWeek.Wednesday );
DayOut( DayOfWeek.Thursday );
DayOut( DayOfWeek.Friday );
DayOut( DayOfWeek.Saturday );
DayOut( DayOfWeek.Sunday );
}
static void DayOut( DayOfWeek d )
{
string myString = d.ToString();
Console.WriteLine( “{0} = {1} = {2}”, d, myString, (int)
d );
DayOfWeek NewVal = (DayOfWeek) StringToEnum
( typeof(DayOfWeek), myString );
Console.WriteLine( “{0} = {1} = {2}”, d, NewVal, (int)
NewVal );
}
static object StringToEnum( Type t, string Value )
{
foreach ( FieldInfo fi in t.GetFields() )
if ( fi.Name == Value )
return fi.GetValue( null );
throw new Exception( string.Format(“Can’t convert {0} to
{1}”, Value,
t.ToString()) );
}
}
}
Downloads
Download source – 1 Kb