Type.Getenumunderlyingtype() Method In C#

In this post, we are going to explore the Type.GetEnumUnderlying method in C# along with its syntax and illustrations.

What is the Type.GetEnumUnderlying Method?

The Type.GetEnumUnderlying function is employed to retrieve the numeric type associated with an enumeration. Within the C# programming language, this function is located within the System.Type class. It proves beneficial when dealing with the blueprint of an enumeration. By utilizing this function, the fundamental data type storing the enum's elements becomes apparent. Understanding this base type is crucial for tasks such as serialization and arithmetic calculations.

Syntax:

It has the following syntax:

Example

public static Type GetEnumUnderlyingType(Type enumType);

In the provided syntax, the parameters are of Type enum. The enumType refers to the Type entity, which signifies the enumeration type of the enum.

This function retrieves the base integer data type of the enumeration. The datatype could be int, byte, sbyte, short, ushort, long, ulong, uint, etc. If the type is not an enum, this function will return a null value.

Some key points related to the method:

Some primary highlights of the Type.GetEnumUnderlying method are as outlined below:

The values assigned to enum members are stored as values of the underlying type.

Common Base Types: The int type serves as the default underlying type.

Checking the type: This technique is employed to verify the enum's type prior to carrying out operations specific to that enum.

The main use cases are:

Enum values can be serialized and deserialized to facilitate bitwise and arithmetic operations, as well as comparisons with the numeric values of the underlying type.

Example:

Let's consider a C# code snippet to showcase the functionality of the Type.GetEnumUnderlyingType method.

Example

using System;
class Program
{
    enum MembershipLevel : short { Basic, Standard, Premium }
    static void Main()
    {
        MembershipLevel currentLevel = MembershipLevel.Standard;
        Console.WriteLine($"Current membership level: {currentLevel}");
        if (Enum.GetUnderlyingType(typeof(MembershipLevel)) == typeof(short))
        {
            Console.WriteLine("Membership level uses a 16-bit integer for storage.");
        }
        else
        {
            Console.WriteLine("Unexpected underlying type for the MembershipLevel enum.");
        }
    }
}

Output:

The <style> element includes a CSS code snippet for a placeholder diagram. This diagram is styled with a linear gradient background, a border radius of 12 pixels, padding of 40 pixels, and a margin of 20 pixels on the top and bottom. The content is centered within the diagram. Additionally, the placeholder diagram features an icon with a font size of 3rem and text with a color of #9ca3af and a font size of 1rem. </style>

Explanation:

This code snippet demonstrates the significance of utilizing the Type.GetEnumUnderlyingType method. Initially, an enumeration is defined with the short data type, containing 'Basic', 'Standard', and 'Premium' as its enum values, corresponding to 16-bit integers. Within the main function, the enum identifier is set to the Standard level of the enum. Subsequently, the GetEnumUnderlying method is employed to verify the data type of the enum. It then determines and displays whether the enum type is indeed of the short data type. Finally, the program concludes after displaying the outcome of this type check.

Example 2:

Let's consider another instance to demonstrate the Type.GetEnumUnderlyingType Method in C#.

Example

using System;
public class Demo
{
    enum WorkHours { Monday = 8, Tuesday = 7, Wednesday = 8, Thursday = 7, Friday = 6 }
    public static void Main()
    {
        try
        {
            WorkHours today = WorkHours.Wednesday;
            Type type = today.GetType();
            string[] enumNames = type.GetEnumNames();
            Console.WriteLine("GetEnumNames() to return the constant name = " + string.Join(", ", enumNames));
            Type underlyingType = Enum.GetUnderlyingType(type);
            Console.WriteLine("Enum Underlying type = " + underlyingType);
            Console.WriteLine("Listing constants with corresponding working hours:");
            foreach (string enumName in enumNames)
            {
                WorkHours day = (WorkHours)Enum.Parse(type, enumName);
                Console.WriteLine($"{enumName}: {day} hours");
            }
        }
        catch (ArgumentException e)
        {
            Console.WriteLine("Not an enum!");
            Console.Write($"{e.GetType()}: {e.Message}");
        }
    }
}

Output:

The CSS code snippet below illustrates a diagram with a placeholder design element.

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

Explanation:

This code snippet showcases the implementation of Enum.GetUnderlyingType method. Initially, an enumeration named 'WorkHours' is defined with predefined values representing the days of the week. Within the main function, the enum values are stored in a string array through the GetEnumNames function. Subsequently, Enum.GetUnderlyingType is employed to reveal the underlying type of the enum. The script proceeds to iterate over the enum keys, convert them into enum type, and retrieve their associated values. Error management is integrated into the program logic using try and catch blocks for error handling.

Conclusion:

In summary, the Type.GetEnumUnderlyingType function plays a significant role in fetching the fundamental data type utilized for storing the values within an enumeration. This function is a part of the System.Type class and finds diverse applications in everyday scenarios such as serialization, deserialization, bitwise operations, arithmetic calculations, and type validation. Prior to employing this function, programmers should carefully consider the balance between performance and type security, as well as readability and sustainability. By leveraging this function, developers can effectively handle enums, determining their underlying integral type to prevent mistakes and enable a range of advanced operations and strategies.

Input Required

This code uses input(). Please provide values below: