Conditional Switch Statement with Enumeration String Value

by Donn Felker 5. January 2007 21:02

As of recently I've had a few requests for how I handle a string representation of an Enumeration in a conditional switch. If you pass in a string into the switch statement without parsing the enumeration .NET will complain about a constant value being required. Here's how to write switch statement with a string respresentation of the Enumeration. You might find this useful when you store a string value of the enumeration in a data source such as a DB or XML File and you need to get its Enumeration value through code.

A lot of the time developers will get an error when they first attempt to peform a conditional switch without knowing how to do it. The error they get is "a constant value is required". Here's how to actually implement it. :)

 

public enum Product
{
    Word,
    Outlook,
    Excel
}

public void Process(string productName)
{
    switch ((Product)Enum.Parse(typeof(Product), productName.ToString()))
    {
        case Product.Excel:
        // Do something
            break;
        case Product.Outlook:
            // Do Something
            break;
        case Product.Word:
            // Do something
            break;            
    }        
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

Donn Felker

Senior Consultant
MCTS
ScrumMaster
Agile Practitioner

About Me | Books I Recommend

Gotta Pay The Bills


Tag cloud

    Popular Posts

    RecentComments

    Comment RSS

    Calendar

    <<  January 2009  >>
    MoTuWeThFrSaSu
    2930311234
    567891011
    12131415161718
    19202122232425
    2627282930311
    2345678

    View posts in large calendar