Question
In C#, how can I convert an int value to an enum value? I want to understand the correct syntax, how the cast behaves, and how to safely handle values that may not exist in the enum.
Short Answer
By the end of this page, you will understand how to cast an int to an enum in C#, what happens when the integer does or does not match a named enum member, and how to validate enum values safely in real code.
Concept
In C#, an enum is a special value type that gives readable names to numeric constants. Internally, each enum member has an underlying numeric value, which is usually an int unless you specify another numeric type.
That means converting an int to an enum is usually just a cast.
enum Status
{
Pending = 0,
Approved = 1,
Rejected = 2
}
int value = 1;
Status status = (Status)value;
This works because Status is backed by numeric values.
Why this matters:
- Enums make code easier to read than raw numbers.
- Many APIs, databases, and configuration systems store numeric values.
- You often need to convert those numeric values into meaningful enum names inside your application.
Important detail: a cast does not guarantee that the integer is a defined enum member.
For example:
int value = 99;
Status status = (Status)value;
This compiles and runs. status now holds the enum value 99, even though 99 is not explicitly defined in Status.
So there are really two separate ideas:
Mental Model
Think of an enum as a labeled parking lot:
- Each parking space has a number.
- Some spaces also have official labels like
Pending,Approved, andRejected. - Casting an
intto an enum is like saying, "Go to parking spot 1."
If spot 1 exists and is labeled Approved, great.
If you go to spot 99, the number still exists as a numeric position, but there may be no official label for it. C# allows that cast, but your program may need to check whether that spot is one of the valid labeled ones.
So:
- cast = assign the number to the enum type
- validate = make sure the number matches a defined enum member
Syntax and Examples
The basic syntax is:
YourEnum value = (YourEnum)someInt;
Example 1: Basic cast
enum Color
{
Red = 1,
Green = 2,
Blue = 3
}
int number = 2;
Color color = (Color)number;
Console.WriteLine(color); // Green
Here, 2 matches Green, so printing the enum shows Green.
Example 2: Casting an undefined value
enum Color
{
Red = 1,
Green = 2,
Blue = 3
}
int number = 10;
Color color = (Color)number;
Console.WriteLine(color); // 10
This is valid C#, but 10 is not a named member. When printed, it shows 10 instead of a name.
Example 3: Safe validation with Enum.IsDefined
Step by Step Execution
Consider this example:
enum Status
{
Pending = 0,
Approved = 1,
Rejected = 2
}
int rawValue = 1;
Status status = (Status)rawValue;
Console.WriteLine(status);
Step by step:
-
Statusis declared as an enum.Pendinghas value0Approvedhas value1Rejectedhas value2
-
rawValueis assigned1. -
(Status)rawValuecasts the integer1to the enum typeStatus. -
Because
1matches the named memberApproved, now represents .
Real World Use Cases
Casting integers to enums is common when working with external data sources.
Database values
A database may store status codes like:
0= Pending1= Approved2= Rejected
Your C# code can cast those numbers into enums for readability.
API responses
Some APIs return numeric codes instead of descriptive strings. Converting those numbers to enums makes your business logic easier to understand.
Configuration files
A config source may contain numeric values for modes, environments, or feature flags. Enums help map those values to meaningful names.
Interop and legacy systems
Older systems often represent states with integers. Enums provide a safer and clearer wrapper around those values in modern C# code.
Switching application behavior
Once a number is converted to an enum, you can write clearer logic:
switch (status)
{
case Status.Pending:
Console.WriteLine("Waiting for review");
break;
case Status.Approved:
Console.WriteLine("Process the request");
break;
case Status.Rejected:
Console.WriteLine("Notify the user");
break;
}
Real Codebase Usage
In real projects, developers usually do more than just cast.
Validation at boundaries
When reading from a database, API, or file, validate the incoming number before using it.
int statusCode = GetStatusCode();
if (!Enum.IsDefined(typeof(Status), statusCode))
{
throw new ArgumentOutOfRangeException(nameof(statusCode), "Unknown status code.");
}
Status status = (Status)statusCode;
This keeps invalid values from spreading through the application.
Guard clauses
A common pattern is to reject bad values early.
public void ProcessStatus(int statusCode)
{
if (!Enum.IsDefined(typeof(Status), statusCode))
{
throw new ArgumentException("Invalid status code.", nameof(statusCode));
}
Status status = (Status)statusCode;
// Continue safely
}
Model mapping
Enums are often used when mapping raw storage models into domain models.
public Order ()
{
Order
{
Id = row.Id,
Status = (Status)row.StatusId
};
}
Common Mistakes
Mistake 1: Assuming casting validates the value
Broken assumption:
enum Role
{
User = 1,
Admin = 2
}
int number = 99;
Role role = (Role)number; // This succeeds
Why it is a problem:
- The cast works even though
99is not defined. - Your program may silently carry invalid state.
How to avoid it:
if (Enum.IsDefined(typeof(Role), number))
{
Role role = (Role)number;
}
else
{
Console.WriteLine("Invalid role value");
}
Mistake 2: Confusing parsing strings with casting integers
Broken code:
int number = 1;
Role role = Enum.Parse<Role>(number); // Wrong
Why it is wrong:
Enum.Parseis for strings, not integers.- Use a cast for integers.
Correct approach:
Role role = (Role)number;
Comparisons
| Approach | Use when | Example | Notes |
|---|---|---|---|
| Direct cast | You already have an integer | (Status)number | Fast and simple, but does not validate |
Enum.IsDefined + cast | You need to ensure the value is named | Enum.IsDefined(typeof(Status), number) | Good for validation at app boundaries |
Enum.Parse | You have a string like "Approved" | Enum.Parse<Status>("Approved") | Not for integers |
Enum.TryParse | You have user input as text | Enum.TryParse("Approved", out Status s) |
Cheat Sheet
enum Status
{
Pending = 0,
Approved = 1,
Rejected = 2
}
Cast int to enum
int number = 1;
Status status = (Status)number;
Check if the value is defined
bool isValid = Enum.IsDefined(typeof(Status), number);
Safe pattern
if (Enum.IsDefined(typeof(Status), number))
{
Status status = (Status)number;
}
else
{
Console.WriteLine("Invalid value");
}
Remember
- Enums are numeric underneath.
- A cast does not validate.
- Undefined numeric values can still be stored in an enum variable.
Enum.ParseandEnum.TryParseare for strings.- Default enum underlying type is usually
int. [Flags]enums may allow combined values like for .
FAQ
How do I convert an int to an enum in C#?
Use a cast:
Status status = (Status)number;
Does casting an int to an enum throw an exception if the value is invalid?
No. C# allows the cast even if the number is not a named enum member.
How do I check whether an int is a valid enum value?
Use Enum.IsDefined:
Enum.IsDefined(typeof(Status), number)
Should I always validate before casting?
Validate when the value comes from outside your code, such as a database, API, file, or user input.
What is the difference between casting and Enum.Parse?
Casting is for numeric values. Enum.Parse is for strings.
Why does Console.WriteLine print a number instead of an enum name?
That happens when the enum variable contains a numeric value that is not defined as a named enum member.
Can enums use types other than int?
Yes. An enum can have another integral underlying type such as byte, short, or long.
Can I cast combined values into a enum?
Mini Project
Description
Build a small console program that reads numeric status codes and converts them into a C# enum. This demonstrates both direct casting and safe validation, which is useful when handling values from databases, APIs, or imported files.
Goal
Create a console app that converts integer status codes into enum values and rejects invalid codes safely.
Requirements
- Create an enum named
OrderStatuswith at least three named values. - Read or define a list of integer status codes.
- Convert valid integers to enum values.
- Detect and report invalid integers.
- Print a friendly message for each processed status code.
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.