C#

Get int value from enum in C# 

Enums in C# are a powerful way to define named constants. However, developers often need to retrieve the underlying integer value of an enum for comparisons, calculations, or storage. In this article, we will explore how to get int value from enum in C# with detailed explanations, examples, real-world use cases, and best practices. This guide is perfect for beginners to intermediate C# developers.

What is an Enum in C#?

An enum (short for enumeration) in C# is a value type that allows you to define a set of named constants. Enums improve code readability and make it easier to maintain.

Basic Syntax of Enum

enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }

By default, the first enumerator has the value 0, and each successive enumerator increases by 1. For example, DaysOfWeek.Sunday equals 0, DaysOfWeek.Monday equals 1, and so on.

Why You Might Need to Get int Value from Enum in C#

Getting the integer value of an enum is common in several real-world scenarios:

  • Storing enum values in a database.
  • Sending enum values in APIs as integers.
  • Performing mathematical operations based on enum values.
  • Comparing enums with other numeric values.

Storing Enum Values in a Database in C#

Enums are commonly used in C# to represent a set of named constants. When working with databases, you often need to store these enum values efficiently. Storing enums as integers is a best practice because it:

  • Reduces storage space compared to strings.
  • Improves query performance.
  • Makes it easier to maintain and update the enum definitions in the code.

Example: Storing Enum Values as Integers

enum OrderStatus { Pending = 1, Processing = 2, Completed = 3, Cancelled = 4 } // Example of inserting an enum into a SQL database OrderStatus status = OrderStatus.Processing; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); string query = "INSERT INTO Orders (Status) VALUES (@Status)"; using (SqlCommand cmd = new SqlCommand(query, conn)) { cmd.Parameters.AddWithValue("@Status", (int)status); cmd.ExecuteNonQuery(); } }

In this example:

  • The enum OrderStatus defines possible order states.
  • The enum is cast to int before inserting it into the database.
  • This ensures only numeric values are stored, which are more efficient than strings.

Retrieving Enum Values from the Database

When reading enum values from the database, you can convert the integer back to the corresponding enum type using casting or Enum.ToObject:

int statusValueFromDb = 3; // Example retrieved from database OrderStatus status = (OrderStatus)statusValueFromDb; Console.WriteLine(status); // Output: Completed

Advantages of Storing Enum Values as Integers

Advantage Description
Efficient Storage Integers use less space in the database compared to strings.
Faster Queries Numeric comparisons are faster than string comparisons.
Consistency Changes to enum names in code won’t affect database values.
Type Safety Using enums in C# ensures only valid values are assigned and retrieved.


  • Always assign explicit numeric values to enum members for clarity and backward compatibility.
  • Use enums consistently in both code and database to avoid mismatches.
  • Document what each integer value represents in the database schema.
  • Consider using a lookup table for large enums to improve maintainability.

By following these practices, storing enum values in a database becomes reliable, efficient, and easy to maintain in your C# applications.

How to Get int Value from Enum in C#

The primary method to get an integer value from an enum in C# is by using explicit casting.

Example 1: Basic Casting

enum Status { Pending = 1, Approved = 2, Rejected = 3 } class Program { static void Main() { Status currentStatus = Status.Approved; int statusValue = (int)currentStatus; Console.WriteLine("The integer value of " + currentStatus + " is " + statusValue); } }

Example 2: Using Enum.GetValues for Multiple Values

foreach (int value in Enum.GetValues(typeof(Status))) { Console.WriteLine(value); }

This loop prints all integer values of the Status enum:

  • 1
  • 2
  • 3

Advanced Tips for Working with Enum Int Values

Assign Custom Values to Enums

enum ErrorCode { NotFound = 404, ServerError = 500, Unauthorized = 401 }

You can assign specific integers to enum members instead of relying on default values. This is useful when enums represent HTTP status codes or other standardized numeric values.

Convert Enum to int Using Convert.ToInt32()

Status currentStatus = Status.Rejected; int intValue = Convert.ToInt32(currentStatus); Console.WriteLine(intValue); // Output: 3

 Use Cases of Enum to Int Conversion in C#

Use Case Description Example
Database Storage Store enum values as integers in SQL databases for efficiency.
INSERT INTO Orders (Status) VALUES ((int)Status.Pending);
API Communication Send enum values as integers in JSON payloads.
var json = JsonConvert.SerializeObject((int)Status.Approved);
Conditional Logic Use numeric comparison or switch statements on enum values.
if ((int)Status.Rejected == 3) { /* Handle rejection */ }

Using Enum Int Values in C#

  • Always use explicit casting or Convert.ToInt32() for clarity.
  • Assign meaningful numeric values when enums represent standard codes.
  • Document enum values to avoid confusion when using integers.
  • Prefer enums over magic numbers to improve code readability.


Getting the integer value from an enum in C# is a simple yet essential technique. By using explicit casting or Convert.ToInt32(), you can easily retrieve enum values for storage, communication, or logic operations. Following best practices ensures your code is readable, maintainable, and ready for real-world applications.

FAQs on Getting int Value from Enum in C#

1. Can enums have negative integer values?

Yes, enums in C# can have negative values. For example:

enum Temperature { Cold = -1, Warm = 0, Hot = 1 }

2. What happens if I cast an enum value that doesn’t exist?

Casting an integer that doesn’t match any enum member is allowed but may result in an undefined enum value:

Status status = (Status)5; Console.WriteLine(status); // Output: 5 (not defined in enum)

3. How do I convert a string to an enum and then get its int value?

string statusString = "Approved"; Status status = (Status)Enum.Parse(typeof(Status), statusString); int value = (int)status; Console.WriteLine(value); // Output: 2

4. Can enums have underlying types other than int?

Yes, enums can have other integral types like byte, short, long, etc. Example:

enum Priority : byte { Low = 1, Medium = 2, High = 3 }

5. Why is using enums better than constants?

  • Enums provide type safety.
  • They improve readability.
  • They group related values logically.
  • They reduce errors compared to magic numbers.
line

Copyrights © 2024 letsupdateskills All rights reserved