How to convert a string to an enum in C#?
Below are a few ways to convert a string to an enum in C#. Both approaches require you to know the target enum type at compile time.
Using Enum.Parse
public enum Colors { Red, Green, Blue } string colorName = "Red"; Colors colorEnum = (Colors)Enum.Parse(typeof(Colors), colorName); // colorEnum is Colors.Red
- Throws an exception if the string doesn’t match an enum member name.
- This approach is case-sensitive by default.
Using Enum.TryParse
public enum Colors { Red, Green, Blue } string colorName = "green"; bool success = Enum.TryParse(colorName, out Colors result); // success is true, result is Colors.Green if match is found
- Does not throw an exception on failure, making it safer for user input.
- You can pass a second parameter to make it case-insensitive:
Enum.TryParse(colorName, true, out Colors result);
Best Practices
- Validate user input before parsing to avoid exceptions or invalid values.
- Consider
Enum.IsDefined(typeof(MyEnum), value)
if you need a strict check for valid enum members. - For flexible user input, use
Enum.TryParse(..., true, out ...)
to allow case-insensitive parsing.
Grow Your C# Skills
Understanding how to handle enums and string conversions is just one part of writing robust .NET applications. To further polish your coding fundamentals and get ready for interviews, explore:
- Grokking the Coding Interview: Patterns for Coding Questions
- Grokking Data Structures & Algorithms for Coding Interviews
For additional insights on C# best practices and system design, check out the DesignGurus.io YouTube channel.
CONTRIBUTOR
TechGrind