Question

How to Cast an int to an Enum in C#

csharpenumscastinginteger

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:

  • Casting: turning the numeric value into the enum type
  • Validation: checking whether that numeric value is one of the named enum members

In real programs, both often matter.

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, and Rejected.
  • Casting an int to 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
Take Quiz

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

enum Color
{
    Red = 1,
    Green = 2,
    Blue = 3
}

int number = 2;

if (Enum.IsDefined(typeof(Color), number))
{
    Color color = (Color)number;
    Console.WriteLine(color);
}
else
{
    Console.WriteLine("Invalid enum value");
}

This checks whether the integer is a named member before using it.

Example 4: Using Enum.ToObject

object value = Enum.ToObject(typeof(Color), 3);
Color color = (Color)value;

Console.WriteLine(color); // Blue

This is less common than a direct cast, but useful in some generic or reflection-based code.

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:

  1. Status is declared as an enum.

    • Pending has value 0
    • Approved has value 1
    • Rejected has value 2
  2. rawValue is assigned 1.

  3. (Status)rawValue casts the integer 1 to the enum type Status.

  4. Because 1 matches the named member Approved, status now represents Status.Approved.

  5. Console.WriteLine(status) prints Approved.

Now look at a different input:

int rawValue = 5;
Status status = (Status)rawValue;
Console.WriteLine(status);

What changes?

  1. rawValue is 5.
  2. C# still allows the cast.
  3. status now contains the enum value 5.
  4. Since 5 is not a named member, Console.WriteLine(status) prints 5.

This shows why casting and validation are different concerns.

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 = Pending
  • 1 = Approved
  • 2 = 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;
}
Take Quiz

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 MapOrder(OrderRow row)
{
    return new Order
    {
        Id = row.Id,
        Status = (Status)row.StatusId
    };
}

In stricter systems, validation may happen before this mapping step.

Logging unexpected values

Sometimes developers allow unknown enum values but log them for investigation.

Status status = (Status)statusCode;

if (!Enum.IsDefined(typeof(Status), statusCode))
{
    Console.WriteLine($"Unexpected status code: {statusCode}");
}

Using enums for readable branching

After conversion, enums improve maintainability:

  • clearer switch statements
  • fewer magic numbers
  • easier refactoring
  • better self-documenting code

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 99 is 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.Parse is for strings, not integers.
  • Use a cast for integers.

Correct approach:

Role role = (Role)number;

Mistake 3: Forgetting the enum's underlying values

enum Size
{
    Small,
    Medium,
    Large
}

These values are actually:

  • Small = 0
  • Medium = 1
  • Large = 2

If you assume different numbers, your cast may produce unexpected results.

Mistake 4: Using raw numbers everywhere

if (statusCode == 2)
{
    // What does 2 mean?
}

This is harder to read than:

if ((Status)statusCode == Status.Rejected)
{
    // Clear meaning
}

Mistake 5: Ignoring flags enums

If an enum is marked with [Flags], combined numeric values may be valid even if they are not a single named member.

[Flags]
enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4
}

Permissions p = (Permissions)3; // Read | Write

In this case, validation rules may be different from ordinary enums.

Comparisons

ApproachUse whenExampleNotes
Direct castYou already have an integer(Status)numberFast and simple, but does not validate
Enum.IsDefined + castYou need to ensure the value is namedEnum.IsDefined(typeof(Status), number)Good for validation at app boundaries
Enum.ParseYou have a string like "Approved"Enum.Parse<Status>("Approved")Not for integers
Enum.TryParseYou have user input as textEnum.TryParse("Approved", out Status s)Safer than Parse for strings
Enum.ToObjectYou need generic or reflection-based enum conversionEnum.ToObject(typeof(Status), number)Less common in everyday code

Cast vs parse

  • Use cast for numeric values.
  • Use parse for string values.

Enum vs constants

EnumConstants
Groups related named numeric valuesSeparate values with no shared enum type
Type-safe in many situationsLess type-safe
Better for switch and domain statesUseful for unrelated fixed values

Validated cast vs unchecked cast

StyleBenefitTrade-off
Unchecked castShort and simpleInvalid values can slip through
Validated castSafer and clearerSlightly more code
Take Quiz

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.Parse and Enum.TryParse are for strings.
  • Default enum underlying type is usually int.
  • [Flags] enums may allow combined values like 3 for 1 | 2.

Common outputs

Console.WriteLine((Status)1); // Approved
Console.WriteLine((Status)99); // 99

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 [Flags] enum?

Yes. Combined numeric values are common with [Flags] enums, such as 3 meaning Read | Write.

Take Quiz

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

  1. Create an enum named OrderStatus with at least three named values.
  2. Read or define a list of integer status codes.
  3. Convert valid integers to enum values.
  4. Detect and report invalid integers.
  5. Print a friendly message for each processed status code.
Take Quiz

Keep learning

Related questions

View more