Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An enumeration (enum) in C# is a distinct value type consisting of a set of named constants, which are fundamentally backed by an integral numeric type known as the underlying type. By default, the C# compiler assigns int (System.Int32) as the underlying type for all enumerations. The underlying type dictates both the memory footprint of the enum and the valid range of numeric values it can represent. You can explicitly declare the underlying type to be any of the following built-in integral types: byte, sbyte, short, ushort, int, uint, long, or ulong. To specify an underlying type other than int, append a colon (:) followed by the desired integral type to the enum identifier.
enum EnumName : underlying_type
{
    // Enumerator list
}

Memory Allocation and Value Bounds

When you define the underlying type, the compiler enforces the value bounds of that specific integral type. If an assigned value exceeds the capacity of the underlying type, a compile-time error occurs.
// Allocates 1 byte per instance. Range: 0 to 255.
enum ProcessState : byte
{
    Idle = 0,
    Running = 1,
    Terminated = 255 
    // Faulted = 256 // Compile-time error: Constant value '256' cannot be converted to a 'byte'
}

// Allocates 8 bytes per instance. Range: 0 to 18,446,744,073,709,551,615.
enum HashFlags : ulong
{
    None = 0,
    FlagA = 1,
    FlagB = 0xFFFFFFFFFFFFFFFF 
}
If values are not explicitly assigned, the compiler initializes the first enumerator to 0 and increments each subsequent enumerator by 1, strictly within the bounds of the declared underlying type.

Type Conversion

C# enforces strong typing for enumerations. Implicit conversions between an enum type and its underlying integral type are prohibited, with the sole exception of the literal 0, which can be implicitly converted to any enum type. All other conversions require an explicit cast.
enum StatusCode : short
{
    Success = 200,
    NotFound = 404
}

// Explicit cast from enum to underlying type
short numericValue = (short)StatusCode.Success; 

// Explicit cast from underlying type to enum
StatusCode status = (StatusCode)404; 

// Implicit conversion of literal 0
StatusCode defaultStatus = 0; 

Runtime Type Inspection

The underlying type of an enum can be inspected at runtime using Reflection. The System.Enum class provides the GetUnderlyingType method specifically for this purpose.
Type enumType = typeof(StatusCode);
Type underlyingType = Enum.GetUnderlyingType(enumType);

Console.WriteLine(underlyingType.Name); // Outputs: Int16
Master C# with Deep Grasping Methodology!Learn More