How to convert a string to an Enum in C#?

NicolasBrondinBernard

Author
@NicolasBrondinBernard

Learn how to convert a string to an enum in just a few lines of code!

Article published on 06/11/2022, last updated on 10/08/2026

C# being a strictly typed language, so even if a string matches perfectly the value of an enum, it cannot be automatically cast.

Solution

To transform/convert a string into an enum value, you will need to use the following method:

bool success = Enum.TryParse("stringValue", out TestEnum enumValue);

This Enum.TryParse method is available in .NET Core and .NET Framework ≥4.0, and the "out" keyword will allow you to initialize and assign a variable directly by passing it as a parameter to the function (available in C#7).

Here is a code containing all the context to see things more clearly:


enum TestEnum
{
    Zero,
    One
}

static void Main(string[] args)
{
    string rawValue = "Zero";
    bool success = Enum.TryParse(rawValue, out TestEnum enumValue);
    if (success) {
        Console.WriteLine(enumValue.ToString());
    } else
    {
        Console.WriteLine("Couldn't convert");
    }
}

Warning: Even when the conversion fails, the output variable (with the out keyword) will be set by default to the first value of the Enum!

You must therefore always have a condition that checks the return state of the Enum.TryParse method!


Fotis Fotopoulos sur Unsplash

Finished reading this article?
Our complete courses
Take it to the next level with our courses!

Complete courses, exercises and certificates to really learn programming!

4.8 average rating

Comments (0)

to leave a comment

No comments yet