Welcome to Bilal Haidar [MVP, MCT] Official Blog Sign in | Join | Help

String Enumeration in C#

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

Published Friday, May 12, 2006 2:12 AM by BilalHaidar [MVP]

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: String Enumeration in C#

That code helped me a lot. Thxs man!
Wednesday, May 31, 2006 2:00 PM by Guillermo

# re: String Enumeration in C#

You have a nice simple solution to the specific problem.

A more generic approach to this is to use a class that emulates enum behavior but allows arbitrary types instead of only numeric integer types. I'd stick with your solution for this simple need, but where more complex behavior is required you might want to take a look at the code I wrote for SpecializedEnum on CodePlex as well.

Thursday, May 29, 2008 8:09 AM by James Coe

Leave a Comment

(required) 
required 
(required)