Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format enum with flags attribute as hex value?

I try to display enum values using the enums ToString method. The enum has the Flags attribute.

There are values that don't match any combination of the enum values.
In this case, ToString returns the number as decimal, but I want to display it as a hex string.

Using ToString("X8") will always return the hex value.

I tried Enum.IsDefined, but it returns only true on non-combined values.

Example:

0x00000201 -> "XXt, TSW_AUTO_DETECT"   (known values)
0x00010108 -> "00010108"               (unknown value)

Q: How to "ToString" unknown enum values as hex value?

like image 903
joe Avatar asked May 24 '26 09:05

joe


1 Answers

You could check if the value has any other bits set than the total bit mask of the flags enumeration. If so, return the number, otherwise the normal tostring:

public static string GetDescription(EnumName value)
{
    var enumtotal = Enum.GetValues(typeof(EnumName)).Cast<int>().Aggregate((i1, i2) => i1 | i2); //this could be buffered for performance
    if ((enumtotal | (int)value) == enumtotal)
        return value.ToString();
    return ((int)value).ToString("X8");
}
like image 174
Me.Name Avatar answered May 26 '26 21:05

Me.Name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!