CodeBlanks Logo Icon CodeBlanks

Enum casting

C# course · Beginner · Lesson 102/116

Learn to convert between enums and int.

Casting enum to int

To convert an enum value to its underlying integer, use the (int) cast. This is useful when you need to use the enum value in a calculation or write it to a database as a number. The cast is a compile-time operation.

For example, in enum Color { Red, Green, Blue }, the expression (int)Color.Green gives 1. Here Color.Green is essentially an integer, kept as an enum only for type safety. When the numeric counterpart is needed, you cast.

Casting int to enum

The reverse is also possible: you can convert an integer to an enum with the form (EnumName). This is useful for turning a numeric code read from a database into an enum value. Beware: the cast succeeds even if the number has no matching member.

For example, Color c = (Color)1; assigns Color.Green to c. But (Color)99 also compiles and runs; it just prints 99. That is why checking validity with Enum.IsDefined before the cast is a good habit.

Checking for invalid values

A cast succeeds even when an integer has no matching enum member, which can lead to unexpected behaviour. To prevent this, you check whether a value is a valid enum member with Enum.IsDefined(typeof(EnumName), value).

For example, if (Enum.IsDefined(typeof(Color), 99)) { ... } returns false because Color has no 99. This sets up a safe gate before the cast and keeps invalid values from breaking your program.

Exercise Print the status as int

Define an enum called Status with members Active, Inactive, Pending. In Main, assign Status.Pending to s as Status s = Status.Pending; and print (int)s with Console.WriteLine.

Show example solution
Define enum Status { Active, Inactive, Pending }, then add Status s = Status.Pending; and Console.WriteLine((int)s);
Example solution:
using System;

enum Status { Active, Inactive, Pending }

class Program
{
    static void Main()
    {
        Status s = Status.Pending;
        Console.WriteLine((int)s);
    }
}

Test yourself

  1. What does (int)Color.Green return?

    enum Color { Red, Green, Blue }
    • 0
    • 2
    • Green
    • 1
    Show answer

    1 — Correct! Green is the second member, so the (int) cast gives 1.

  2. Convert the number to enum

    int code = 2;
    Color c = ____;
    Console.WriteLine(c);
    Show answer
    int code = 2;
    Color c = (Color)code;
    Console.WriteLine(c);
  3. Match the operation with its result

    (int)Color.Red
    0
    (Color)1
    Color.Green
    Enum.IsDefined
    validity check

All lessons in Beginner