← All articles

Conditional Switch Statement with Enumeration String Value

How to switch on a string value of a C# enum without hitting the 'a constant value is required' compiler error - just Enum.Parse it first.

Donn Felker

Donn Felker

2007.01.06 · 1 min read

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

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading