Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a flags enum to convert to UInt64 with a TypeConverter

I have a class which takes a generic class TState in its constructor, under the condition that TState can be converted to a UInt64using a TypeConverter. It will then be used as flags.

I want to use a [Flags] enum for TState, but even if I define it as

[Flags]  
public enum EState : ulong
{
    None = 0x0,
    State1= 0x1,
    State2= 0x2,
    State3= 0x4
}

then if TypeConverter typeConv = TypeDescriptor.GetConverter(typeof(EState)); typeConv.CanConvertTo(typeof(UInt64))is false.

How can I make an enum which will convert appropriately? Thanks!

like image 885
Joel in Gö Avatar asked Jan 28 '26 00:01

Joel in Gö


1 Answers

You can use Convert.ChangeType():

[Flags]
private enum MyEnum1 : ulong 
{
   A =1,
   B = 2
}

And then

MyEnum1 enum1 = MyEnum1.A | MyEnum1.B;
ulong changeType = (ulong) Convert.ChangeType(enum1, typeof (ulong));

UPDATE

Why TypeDescriptor does not work?

According to docs:

This method looks for the appropriate type converter by looking for a TypeConverterAttribute. If it cannot find a TypeConverterAttribute, it traverses the base class hierarchy of the class until it finds a primitive type.

TypeDescriptor and TypeConvertor work with ExpandableObjectConverter while Convert works with IConvertible.

like image 142
Aliostad Avatar answered Jan 30 '26 13:01

Aliostad



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!