const_ref
const_ref

Reputation: 4096

Convert a Flag Enum to another Flag Enum in C#

I have two Flag enums that look something like the following

[Flags]
public enum EnumTypeOne: ulong
{
    NONE                    = 0,
    STUFF_ONE               = ( 1 << 0 ),
    STUFF_TWO               = ( 1 << 1 )
}

[Flags]
public enum EnumTypeTwo: ulong
{
    NONE                    = 0,
    STUFF_ONE               = ( 1 << 0 ),
    STUFF_TWO               = ( 1 << 1 )
}

One enum is inside one class library(internal use only) and the other will be supplied as dll.

Internally I would like to marshall between these two enums since they are identical. I know how to do this with a regular enum however it does not seem to work if more than one flag is set on one of the enums.

I have tried using the following solution

var enumResult = (EnumTypeOne)Enum.Parse(typeof(EnumTypeOne), Enum.GetName(typeof(EnumTypeTwo), mEnumTypeTwo);

As stated above this only works if only a single flag is in use, the use of multiple flags calls it to fall over.

Is there a solution to allow me to convert between the two enums efficiently?

Upvotes: 3

Views: 1966

Answers (1)

Alberto
Alberto

Reputation: 15941

just cast it

EnumTypeOne a = EnumTypeOne.STUFF_ONE|EnumTypeOne.STUFF_TWO;
EnumTypeTwo b = (EnumTypeTwo)a;

Upvotes: 13

Related Questions