Question

How to Convert a String to an Enum in C#

csharpstringenums

Question

In C#, what is the best way to convert a string into an enumeration value?

For example, an HTML <select> element contains values that represent members of an enum. After the form is submitted, the selected value is received as a string, and I want to convert that string into the matching enum value.

A simplified example of the desired behavior is:

CopyStatusEnum myStatus = StatusEnum.Parse("Active");

However, that is not valid C# syntax. What is the correct way to parse a string into an enum value?

Short Answer

By the end of this page, you will understand how to convert strings into enum values in C#, when to use Enum.Parse versus Enum.TryParse, how to safely handle invalid input, and how this commonly appears in web forms, APIs, and application code.

Concept

In C#, an enum is a type that represents a fixed set of named constants. Enums make code easier to read because you can use meaningful names like Active, Pending, or Archived instead of raw numbers.

When data comes from outside your program—such as an HTML form, query string, JSON payload, configuration file, or database—it often arrives as a string. If that string is meant to represent an enum member, you need to convert it into the actual enum type before using it safely in your code.

C# provides built-in tools for this:

  • Enum.Parse(...) converts a string to an enum value, but throws an exception if the string is invalid.
  • Enum.TryParse(...) attempts the conversion and returns true or false instead of throwing an exception.

This matters in real programs because user input is not always reliable. Safe enum parsing helps prevent crashes and makes validation clearer.

For most modern C# code, Enum.TryParse<TEnum>(...) is the preferred approach because it is safer and easier to use with external input.

Mental Model

Think of an enum like a menu with a fixed list of valid choices:

  • Active
  • Inactive
  • Deleted

A string is just text someone typed or selected, like a note that says "Active".

Parsing is the process of checking whether that note matches one of the official menu options and, if it does, turning it into the real enum value your program understands.

So:

  • A string is a label written on paper.
  • An enum value is the official item in your system.
  • Parsing is the act of matching the label to the official item.

If the label is wrong, your program either:

  • throws an error with Enum.Parse, or
  • safely reports failure with Enum.TryParse.
Take Quiz

Syntax and Examples

Basic enum definition

public enum CopyStatusEnum
{
    Active,
    Inactive,
    Deleted
}

Using Enum.Parse

string input = "Active";
CopyStatusEnum status = (CopyStatusEnum)Enum.Parse(typeof(CopyStatusEnum), input);

This works, but it throws an exception if input does not match a valid enum member.

Using Enum.TryParse (recommended)

string input = "Active";

if (Enum.TryParse<CopyStatusEnum>(input, out var status))
{
    Console.WriteLine(status); // Active
}
else
{
    Console.WriteLine("Invalid status value.");
}

This is safer because it does not throw an exception for invalid input.

Ignoring letter case

string input = "active";

if (Enum.TryParse<CopyStatusEnum>(input, ignoreCase: true, out var status))
{
    Console.WriteLine(status); // Active
}

This is useful when input may be lowercase, uppercase, or mixed case.

Example from form input

string selectedValue = "Inactive";

if (Enum.TryParse<CopyStatusEnum>(selectedValue, true, out var status))
{
    // Use status in your business logic
    Console.WriteLine($"Selected status: {status}");
}
else
{
    Console.WriteLine("The selected value is invalid.");
}

The important idea is that the string must match an enum member name unless you intentionally handle numeric values too.

Step by Step Execution

Consider this example:

public enum CopyStatusEnum
{
    Active,
    Inactive,
    Deleted
}

string input = "Inactive";

if (Enum.TryParse<CopyStatusEnum>(input, out var status))
{
    Console.WriteLine($"Parsed: {status}");
}
else
{
    Console.WriteLine("Invalid value");
}

Step-by-step

  1. The enum CopyStatusEnum is defined with three valid values:

    • Active
    • Inactive
    • Deleted
  2. The variable input contains the string "Inactive".

  3. Enum.TryParse<CopyStatusEnum>(input, out var status) checks whether "Inactive" matches one of the enum member names.

  4. Because Inactive exists in the enum, parsing succeeds.

  5. The method returns true.

  6. The parsed enum value is stored in status.

  7. The if block runs and prints:

Parsed: Inactive

What if the input is invalid?

If you change the input to:

string input = "Paused";

Then:

  1. TryParse checks the enum.
  2. Paused is not a valid member.
  3. The method returns false.
  4. The else block runs.

This lets you handle bad input without crashing the program.

Real World Use Cases

Enums parsed from strings appear in many common scenarios:

Web forms

A <select> field may submit values like "Active" or "Deleted", which need to be converted into an enum before saving or processing.

APIs

A request body or query parameter might include status text:

{
  "status": "Active"
}

Your C# code may need to convert that string to an enum for validation and business rules.

Configuration files

Application settings often store modes as strings such as "Development", "Production", or "Testing".

Command-line tools

A CLI app may accept arguments like:

myapp --mode Active

That mode string is often parsed into an enum.

Database or CSV imports

Imported text values may need to be converted to enums before they can be used consistently in the system.

Take Quiz

Real Codebase Usage

In real projects, developers usually avoid direct Enum.Parse on untrusted input and instead use safer patterns.

Pattern: validation with TryParse

if (!Enum.TryParse<CopyStatusEnum>(input, true, out var status))
{
    return "Invalid status provided.";
}

This is common in controllers, services, and import routines.

Pattern: guard clause

if (string.IsNullOrWhiteSpace(input))
{
    throw new ArgumentException("Status is required.");
}

if (!Enum.TryParse<CopyStatusEnum>(input, true, out var status))
{
    throw new ArgumentException("Invalid status.");
}

Guard clauses reject bad input early.

Pattern: combine parsing with Enum.IsDefined

Sometimes developers want to reject numeric values or undefined values explicitly:

if (Enum.TryParse<CopyStatusEnum>(input, true, out var status) &&
    Enum.IsDefined(typeof(CopyStatusEnum), status))
{
    Console.WriteLine("Valid enum name");
}
else
{
    Console.WriteLine("Invalid enum value");
}

This is useful because TryParse may accept numeric strings such as "1" if the underlying enum type allows it.

Pattern: model binding in ASP.NET

In ASP.NET applications, frameworks often bind enums automatically when input matches expected values. Still, manual parsing is useful when:

  • input names differ from enum names
  • custom validation is needed
  • values come from less structured sources

Pattern: fallback default

CopyStatusEnum status = Enum.TryParse<CopyStatusEnum>(input, true, out var parsed)
    ? parsed
    : CopyStatusEnum.Inactive;

This can be helpful, but only when a default makes sense and does not hide invalid data.

Common Mistakes

1. Forgetting to cast when using Enum.Parse

Broken code:

CopyStatusEnum status = Enum.Parse(typeof(CopyStatusEnum), "Active");

Why it fails:

  • Enum.Parse returns object, so you must cast it.

Correct version:

CopyStatusEnum status = (CopyStatusEnum)Enum.Parse(typeof(CopyStatusEnum), "Active");

2. Using Enum.Parse on unsafe user input

Broken idea:

var status = (CopyStatusEnum)Enum.Parse(typeof(CopyStatusEnum), userInput);

Why it is risky:

  • Invalid input throws an exception.

Safer version:

if (Enum.TryParse<CopyStatusEnum>(userInput, out var status))
{
    // safe to use
}

3. Not handling case differences

Broken code:

Enum.TryParse<CopyStatusEnum>("active", out var status);

This may fail if case-sensitive matching is used.

Better version:

Enum.TryParse<CopyStatusEnum>("active", ignoreCase: true, out var status);

4. Assuming any parsed value is a named enum member

This can be surprising:

public enum CopyStatusEnum
{
    Active = 1,
    Inactive = 2
}

Enum.TryParse<CopyStatusEnum>("1", out var status);

This succeeds, and status becomes Active.

If you only want named values from strings like "Active", combine parsing with Enum.IsDefined.

5. Mixing up enum type names

Broken code:

CopyStatusEnum myStatus = StatusEnum.Parse("Active");

Why it is wrong:

  • Parse is a method on Enum, not on your enum type.
  • The enum type name must match the real type.

Correct version:

CopyStatusEnum myStatus = (CopyStatusEnum)Enum.Parse(typeof(CopyStatusEnum), "Active");

6. Ignoring empty input

Broken code:

Enum.TryParse<CopyStatusEnum>("", out var status);

Avoid this by checking first:

if (string.IsNullOrWhiteSpace(input))
{
    Console.WriteLine("Status is required.");
}

Comparisons

ApproachWhat it doesInvalid input behaviorBest use case
Enum.ParseConverts string to enumThrows exceptionTrusted input when failure should be exceptional
Enum.TryParseAttempts conversionReturns falseUser input, forms, APIs, files
Manual if/else mappingMatches strings yourselfFully custom behaviorWhen input values do not match enum names

Enum.Parse vs Enum.TryParse

// Parse
var status1 = (CopyStatusEnum)Enum.Parse(typeof(CopyStatusEnum), "Active");

// TryParse
if (Enum.TryParse<CopyStatusEnum>("Active", out var status2))
{
    Console.WriteLine(status2);
}

TryParse is usually better for beginner and production code because it avoids exceptions for normal validation failures.

Automatic binding vs manual parsing

OptionBenefitDrawback
Automatic framework bindingLess codeLess control over custom validation
Manual parsingFull controlMore code to maintain

Name-based input vs numeric input

Input typeExampleNotes
Enum name"Active"Most readable and safest for forms/APIs
Numeric string"1"Can work, but is less clear and easier to misuse
Take Quiz

Cheat Sheet

Quick syntax

// Safe parsing
if (Enum.TryParse<MyEnum>(input, out var value))
{
    // use value
}

// Safe parsing, ignore case
if (Enum.TryParse<MyEnum>(input, true, out var value))
{
    // use value
}

// Parse with exception on failure
MyEnum value = (MyEnum)Enum.Parse(typeof(MyEnum), input);

Rules to remember

  • Enum.Parse returns object, so cast it.
  • Enum.TryParse is safer for user input.
  • Use ignoreCase: true if input might differ in capitalization.
  • TryParse may accept numeric strings like "1".
  • Use Enum.IsDefined(...) if you want to ensure the result is a named enum value.

Common safe pattern

if (!string.IsNullOrWhiteSpace(input) &&
    Enum.TryParse<CopyStatusEnum>(input, true, out var status) &&
    Enum.IsDefined(typeof(CopyStatusEnum), status))
{
    // valid named enum value
}

Best default choice

Use:

Enum.TryParse<TEnum>(input, ignoreCase: true, out var value)

for most form, API, and configuration input.

FAQ

How do I convert a string to an enum in C#?

Use Enum.TryParse<TEnum>(input, out var value) for safe parsing, or Enum.Parse(typeof(TEnum), input) if you want an exception on invalid input.

Should I use Enum.Parse or Enum.TryParse?

Use Enum.TryParse for most real-world input because it safely handles invalid values without throwing exceptions.

Can Enum.TryParse ignore uppercase and lowercase differences?

Yes. Use the overload with ignoreCase: true.

Enum.TryParse<MyEnum>(input, true, out var value)

Why does Enum.Parse need a cast?

Because Enum.Parse returns object, not the specific enum type.

Can I parse numeric strings like "1" into an enum?

Yes, in many cases C# allows that. If you only want named values like "Active", also check with Enum.IsDefined.

What happens if the string does not match any enum member?

  • Enum.Parse throws an exception.
  • Enum.TryParse returns false.

Is enum parsing common in ASP.NET forms?

Yes. It is very common when reading submitted form values, route values, query parameters, or API data.

Take Quiz

Mini Project

Description

Build a small C# console program that simulates receiving a status value from a web form and converting it into an enum safely. This demonstrates how to validate external input before using it in your application logic.

Goal

Create a program that reads a status string, attempts to convert it to an enum, and prints either the parsed result or a clear error message.

Requirements

  • Define an enum with at least three status values.
  • Read a string value that represents a selected status.
  • Convert the string to the enum using a safe approach.
  • Ignore letter case during parsing.
  • Reject invalid input with a helpful message.
Take Quiz

Keep learning

Related questions

View more