C# – How to convert string to enum

In this article we’ll explain the way of converting string to any enumeration type. There are two easiest ways to do so: using Parse or TryParse method. Examples of both are presented below. If you need to read how to create and use enums, please see following page: How to use enum.

All examples will use Day enum representing days of week.

Parse method

Parse method is overloaded, so it can receive different set of arguments. Target type can be passed either as a generic T parameter or first argument. Next argument is string value which represents element of desired enumeration. Optionally it is also possible to define whether parsing process should be case sensitive or not (by default it is case sensitive). It can be done via last boolean parameter ignoreCase.

TryParse method

TryParse works very similar to Parse, however it returns boolean value informing whether the process succeeded or not. Target enum is available through output argument. TryParse also can be case sensitive or not, which is decided based on ignoreCase parameter.

Two cases (second and fourth) which failed a parse process, have output values set as Monday. The reason is the way how enums work. Default value is always first element from given enumeration, so when parsing failed, default value has been set.