Not a subscriber?

Join thousands of others who are building self-directed lives through creativity, grit, and digital strategy—breaking free from the 9–5.
Receive one free message a week

Conditional Switch Statement with Enumeration String Value

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;            
    }        
}