Search code examples
c#enumsflags

Is there a way to Add Flag enum to each other without knowing the exact enum type?


I'm finding a way to do sth like this in C#:

// giving eTankComponents is an [Flags] enum

[Flags]
public enum eTankComponents
{
     Empty = 0,
     Barrel = 1,
     wheels = 2,
}

Type enumType = Type.GetType("eTankComponents");
object emptyTank = Enum.Parse(enumType, "Empty");
object tankWithBarrel = Enum.AddFlag(emptyTank, enumType, Enum.Parse(enumType, "Barrel"));
object fullTank = Enum.AddFlag(tankWithBarrel, enumType, Enum.Parse(enumType, "wheels"));`

Is there any Method in c# to do sth like Enum.AddFlag

searched online and found nothing.


Solution

  • You can get the underlying values using Convert.ToInt64 and use bitwise OR on them. Int64 is the largest underlying value type that an enum can have, and this will work for enums with smaller underlying value types too.

    Then you can use ToObject to get the enum value from the underlying value.

    Type enumType = Type.GetType("eTankComponents");
    var barrel = Enum.Parse(enumType, "Barrel");
    var wheels = Enum.Parse(enumType, "Wheels");
    var combined = Convert.ToInt64(barrel) | Convert.ToInt64(wheels);
    
    Console.WriteLine(Enum.ToObject(enumType, combined));