codecorner.tigernews.co.uk

     from TIGER COMPUTER SERVICES LTD

Top Right Logo Spacer
site copyright 2000-2009
     C# (C Sharp) Track Data Access TrackPocket PC TrackSQL Server Track
About the C# (C Sharp) Track Tips and Tricks for C# (C Sharp) Generic Database Access - MDB, SQL Server 2000 and SQL CE

Converting enumeration values to/from String values

When serialising objects to XML, or reading settings from .config files I find it useful to use the actual enumeration names rather than the underlying numeric values behind the enumeration. Human readable values make a lot more sense than cryptic 'magic numbers'.

Converting an enumeration to a string is easy, just use the ToString() method.

Converting back from a string is trickier, but easy once you know how. Just use Enum.Parse as shown in the code sample below.

private enum DailyPeriod
{
    Morning = 1, Afternoon = 2, Evening = 3, Night = 4,
}

static void Main(string[] args)
{
    // enumeration to a string value
    string strVal = DailyPeriod.Night.ToString();
    Console.WriteLine(strVal);

    Console.WriteLine();

    // string value back to enumeration
    DailyPeriod dp = (DailyPeriod)Enum.Parse(typeof(DailyPeriod), "AFTERNOON", true);
    Console.WriteLine(dp);

    Console.ReadLine();
}