0
0
C Sharp (C#)programming~5 mins

Underlying numeric values in C Sharp (C#)

Choose your learning style9 modes available
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.

You have a list of named options and want to save their numbers in a file.
You want to compare two named values by their numbers.
You need to send a named value over the network as a number.
You want to print the number behind a named value for debugging.
Syntax
C Sharp (C#)
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.

Examples
This gets the number 1 from Monday.
C Sharp (C#)
enum Day { Sunday = 0, Monday = 1, Tuesday = 2 }

int dayNumber = (int)Day.Monday;
This gets the number 30 from Blue.
C Sharp (C#)
enum Color { Red = 10, Green = 20, Blue = 30 }

int colorValue = (int)Color.Blue;
Sample Program

This program shows how to get the number behind the enum value 'On'.

C Sharp (C#)
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}");
    }
}
OutputSuccess
Important Notes

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.

Summary

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.