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 returnstrueorfalseinstead 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:
ActiveInactiveDeleted
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.
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, status))
{
Console.WriteLine(status);
}
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
-
The enum
CopyStatusEnumis defined with three valid values:ActiveInactiveDeleted
-
The variable
inputcontains the string"Inactive". -
Enum.TryParse<CopyStatusEnum>(input, out var status)checks whether"Inactive"matches one of the enum member names. -
Because
Inactiveexists in the enum, parsing succeeds. -
The method returns .
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.
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, , status) &&
Enum.IsDefined((CopyStatusEnum), status))
{
Console.WriteLine();
}
{
Console.WriteLine();
}
Common Mistakes
1. Forgetting to cast when using Enum.Parse
Broken code:
CopyStatusEnum status = Enum.Parse(typeof(CopyStatusEnum), "Active");
Why it fails:
Enum.Parsereturnsobject, 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
Comparisons
| Approach | What it does | Invalid input behavior | Best use case |
|---|---|---|---|
Enum.Parse | Converts string to enum | Throws exception | Trusted input when failure should be exceptional |
Enum.TryParse | Attempts conversion | Returns false | User input, forms, APIs, files |
Manual if/else mapping | Matches strings yourself | Fully custom behavior | When input values do not match enum names |
Enum.Parse vs Enum.TryParse
// Parse
var status1 = (CopyStatusEnum)Enum.Parse((CopyStatusEnum), );
(Enum.TryParse<CopyStatusEnum>(, status2))
{
Console.WriteLine(status2);
}
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.Parsereturnsobject, so cast it.Enum.TryParseis safer for user input.- Use
ignoreCase: trueif input might differ in capitalization. TryParsemay 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, , status) &&
Enum.IsDefined((CopyStatusEnum), status))
{
}
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 .
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.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
C# Type Checking Explained: typeof vs GetType() vs is
Learn when to use typeof, GetType(), and is in C#. Understand exact type checks, inheritance, and safe type testing clearly.
C# Version Numbers Explained: C# vs .NET Framework and Why “C# 3.5” Is Incorrect
Learn the correct C# version numbers, how they map to .NET releases, and why terms like C# 3.5 are inaccurate and confusing.