May 12 2006

String Enumeration in C#

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 12:12

I have always had the need to use String Enumerations. What do I mean by that?

Suppose we have this Enum Type:

    public enum StringNames
    {
        Bilal,
        Wessam,
        Elsa,
        Samer,
        Tarek,
        Farah,
        Firas,
        Mohammad
    }

In my code, I would like to have something as:

string _Name = "Bilal";
switch (_Name)
{    
        case StringNames.Bilal:
                break;    
        case StringNames.Wessam:           
                break;     
        case StringNames.Elsa:           
                break;      
        .......
}

Well the above doesn't work as it is. How to make it work?

There is a method called Enum.Parse, there are two overloads, we will be using the one with the IgnoreCase boolean option as follows:

StringNames _StringNames = (StringNames)Enum.Parse(typeof(StringNames), _Name, true);

This will convert the string value "Bilal" contained in _Names, into a EnumType value, so now after executing the above statement, you have:


 _StringNames = StringNames.Bilal

So, StringNames.Bilal is an EnumValue equals the EnumValue _StringNames, so rewriting the above switch statement would be something as:

    string _Name = "Bilal";
    StringNames _StringNames = (StringNames)Enum.Parse(typeof(StringNames),_Name,true);

    switch (_StringNames)
    {
        case StringNames.Bilal:
            break;
        case StringNames.Wessam:
            break;
        case StringNames.Elsa:
            break;
        .......
    }

I want to thank my colleague Raed for uncovering for me the real return type of the Enum.Parse method.

Hope helps you out!

Regards

Tags: ,

Comments are closed