Introduction
Sometimes you want to know the number behind a named value, like a color or a day. This helps when you want to store or compare these values easily.
Sometimes you want to know the number behind a named value, like a color or a day. This helps when you want to store or compare these values easily.
enum Name { Option1 = 1, Option2 = 2 } int number = (int)Name.Option1;
Enums are special named groups of numbers.
You can get the number by casting the enum value to int.
enum Day { Sunday = 0, Monday = 1, Tuesday = 2 } int dayNumber = (int)Day.Monday;
enum Color { Red = 10, Green = 20, Blue = 30 } int colorValue = (int)Color.Blue;
This program shows how to get the number behind the enum value 'On'.
using System; class Program { enum Status { Off = 0, On = 1, Unknown = 99 } static void Main() { Status current = Status.On; int numericValue = (int)current; Console.WriteLine($"The numeric value of {current} is {numericValue}"); } }
By default, enum values start at 0 and increase by 1 unless you set them.
You can cast enum values to their underlying number type to get the number.
Enums group names with numbers.
You get the number by casting the enum value to int.
This helps when you want to store or compare enum values as numbers.
Day.Monday in C#?enum Color { Red = 3, Green, Blue }Console.WriteLine((int)Color.Green);
enum Status { Active = 1, Inactive = 1, Pending = 2 }enum Level { Low = 1, Medium = 5, High = 10 }score matches any enum value?Pass the test and this pattern moves unknown