Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get int value from enum in C#?
In C#, an enum (enumeration) is a value type that represents a group of named constants. By default, each enum value has an underlying integer value starting from 0. You can extract the integer value from an enum using type casting.
Syntax
Following is the syntax for casting an enum to int −
int value = (int)EnumName.EnumValue;
Following is the syntax for declaring an enum −
public enum EnumName { Value1, Value2, Value3 }
Using Default Integer Values
By default, enum values are assigned integer values starting from 0 and incrementing by 1 −
using System;
public class Demo {
public enum Vehicle { Car, Bus, Truck }
public static void Main() {
int a = (int)Vehicle.Car;
int b = (int)Vehicle.Bus;
int c = (int)Vehicle.Truck;
Console.WriteLine("Car = {0}", a);
Console.WriteLine("Bus = {0}", b);
Console.WriteLine("Truck = {0}", c);
}
}
The output of the above code is −
Car = 0 Bus = 1 Truck = 2
Using Custom Integer Values
You can assign custom integer values to enum members. When you specify a value for one member, subsequent members continue incrementing from that value −
using System;
public class Demo {
public enum Status { Active = 10, Inactive = 20, Pending = 25, Complete }
public static void Main() {
Console.WriteLine("Active = {0}", (int)Status.Active);
Console.WriteLine("Inactive = {0}", (int)Status.Inactive);
Console.WriteLine("Pending = {0}", (int)Status.Pending);
Console.WriteLine("Complete = {0}", (int)Status.Complete);
}
}
The output of the above code is −
Active = 10 Inactive = 20 Pending = 25 Complete = 26
Converting All Enum Values to Integers
You can iterate through all enum values and get their integer representations using Enum.GetValues() −
using System;
public class Demo {
public enum Priority { Low = 1, Medium = 5, High = 10 }
public static void Main() {
foreach (Priority priority in Enum.GetValues(typeof(Priority))) {
Console.WriteLine("{0} = {1}", priority, (int)priority);
}
}
}
The output of the above code is −
Low = 1 Medium = 5 High = 10
Conclusion
Getting integer values from enums in C# is straightforward using type casting with (int). Enums provide a way to work with named constants while maintaining their underlying integer values, making them useful for both readability and numeric operations.
