How to get the integral value of an Enum member using Reflection?

224 views Asked by At

Consider the following Enum:

[Flags]
public enum Digit:
    UInt64
{
    None = 00 << 00,

    One = 01 << 00,
    Two = 01 << 01,
    Three = 01 << 02,
    // Etcetera...

    Other = UInt64.MaxValue - 1,
    Unknown = UInt64.MaxValue,
}

var type = typeof(Digit);
// Returns System.String [].
var names = Enum.GetNames(type);
// Returns System.Array.
var values = Enum.GetValues(type);
// Returns IEnumerable<object>.
var values = Enum.GetValues(type).Cast<object>();

Now, I want to get the numeric value of the Enum members without having to cast them to a specific integral type. This is for code generation purposes so below is an example of the code I want to be able to generate:

[Flags]
public enum Digit:
    UInt64
{
    None = 0,

    One = 1,
    Two = 2,
    Three = 4,
    // Etcetera...

    Other = 18446744073709551614,
    Unknown = 18446744073709551615,
}

Of course, I could check the underlying type of the enumeration by calling Enum.GetUnderlyingType(type); and use conditional code to cast each case but was wondering if there is a more direct way.

Please note that I am just looking for the textual representation of the integral value and do not need to do any arithmetic with it or manipulation on it.

Am I missing something simple or is there no way to achieve this without casting?

1

There are 1 answers

2
Matthew Watson On BEST ANSWER

I don't think there's a way to do this without some kind of conversion, but you can do it without having to use conditional code.

For example:

using System;
using System.Linq;

static class Program
{
    [Flags]
    public enum Digit :
        UInt64
    {
        None = 00 << 00,

        One   = 01 << 00,
        Two   = 01 << 01,
        Three = 01 << 02,
        // Etcetera...

        Other   = UInt64.MaxValue - 1,
        Unknown = UInt64.MaxValue,
    }

    public static void Main()
    {
        var type           = typeof(Digit);
        var values         = Enum.GetValues(type);
        var underlyingType = Enum.GetUnderlyingType(type);

        var strings =
            values.Cast<object>()
            .Select(item => Convert.ChangeType(item, underlyingType).ToString())
            .ToArray();

        Console.WriteLine(string.Join(", ", strings));
    }
}

This outputs: 0, 1, 2, 4, 18446744073709551614, 18446744073709551615