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.
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.
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.
Getting the integer value of an enum is common in several real-world scenarios:
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:
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:
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
| 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. |
By following these practices, storing enum values in a database becomes reliable, efficient, and easy to maintain in your C# applications.
The primary method to get an integer value from an enum in C# is by using explicit 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); } }
foreach (int value in Enum.GetValues(typeof(Status))) { Console.WriteLine(value); }
This loop prints all integer values of the Status enum:
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.
Status currentStatus = Status.Rejected; int intValue = Convert.ToInt32(currentStatus); Console.WriteLine(intValue); // Output: 3
| Use Case | Description | Example |
|---|---|---|
| Database Storage | Store enum values as integers in SQL databases for efficiency. |
|
| API Communication | Send enum values as integers in JSON payloads. |
|
| Conditional Logic | Use numeric comparison or switch statements on enum values. |
|
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.
Yes, enums in C# can have negative values. For example:
enum Temperature { Cold = -1, Warm = 0, Hot = 1 }
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)
string statusString = "Approved"; Status status = (Status)Enum.Parse(typeof(Status), statusString); int value = (int)status; Console.WriteLine(value); // Output: 2
Yes, enums can have other integral types like byte, short, long, etc. Example:
enum Priority : byte { Low = 1, Medium = 2, High = 3 }
Copyrights © 2024 letsupdateskills All rights reserved