C# `Type.GetEnumUnderlyingType()`: Determining the Underlying Type of Enumerations
Learn how to determine the underlying integral type (e.g., `int`, `byte`, `short`) used to store enum values in C# using the `Type.GetEnumUnderlyingType()` method. This tutorial explains its functionality, demonstrates its usage with code examples, and highlights its application in situations requiring runtime inspection of enumeration types.
Using C#'s `Type.GetEnumUnderlyingType()` Method
The C# `Type.GetEnumUnderlyingType()` method retrieves the integral type used to store the values of an enumeration (enum). Enums are custom data types that represent a set of named constants.
Understanding Enums and Underlying Types
When you define an enum in C#, its members (named constants) are actually stored as integer values (or other integral types like `byte`, `short`, etc.). The `GetEnumUnderlyingType()` method tells you what this underlying integral type is.
`Type.GetEnumUnderlyingType()` Syntax
public static Type GetEnumUnderlyingType(Type enumType);
This method takes the `Type` object of an enumeration as input and returns a `Type` object representing the underlying integral type. If the input type is not an enum, it returns `null`.
Example 1: Determining the Underlying Type
enum MyEnum : byte { A, B, C } // Underlying type is byte
Type underlyingType = Enum.GetUnderlyingType(typeof(MyEnum));
Console.WriteLine(underlyingType); //Output: System.Byte
Example 2: Handling Non-Enum Types
try {
Type underlyingType = Enum.GetUnderlyingType(typeof(string)); // string is not an enum
Console.WriteLine(underlyingType);
} catch (ArgumentException ex) {
Console.WriteLine($"Error: {ex.Message}");
}
Example 3: Working with Enum Members
public enum Days { Mon, Tue, Wed, Thu, Fri, Sat, Sun }
public class EnumExample {
public static void Main(string[] args) {
// ... (code to get the underlying type and print enum members with their underlying values) ...
}
}
Uses of `Type.GetEnumUnderlyingType()`
- Serialization/Deserialization: Handling enums during data serialization/deserialization.
- Bitwise Operations: Performing bitwise operations on enum values.
- Arithmetic Operations: Performing arithmetic operations with enum values.
- Type Checking: Verifying if a given type is an enum before performing enum-specific operations.