Casting an int to specific Enum at runtime from derived class

I have a group of classes that all are derived from the same base class, and all define unique Enums of the same name.

public class DerivedClassOne : BaseClass
{
    public enum Flags
    {
        None = 0,
        cheese = 1,
        ham = 2,
        egg = 4
    }
}

public class DerivedClassTwo : BaseClass
{
    public enum Flags
    {
        None = 0,
        bacon = 1,
        lettuce = 2,
        tomato = 4
    }
}

How would I, with only an instance of BaseClass, be able to cast an int (n) to this enum and store it at runtime? ie:

object flag = (BaseClassInstance.Enums.Flags)n;

>Solution :

If you don’t mind boxing enums as Enum (which is somewhat better than Object), then you can do this:


public abstract class BaseClass
{
    public abstract Enum ConvertInt32ToSomeEnumType( Int32 value );
}

public class DerivedClassOne : BaseClass
{
    public override Enum ConvertInt32ToSomeEnumType( Int32 value ) => (DerivedClassOne.Flags)value;
}

public class DerivedClassTwo : BaseClass
{
    public override Enum ConvertInt32ToSomeEnumType( Int32 value ) => (DerivedClassTwo.Flags)value;
}

Screenshot proof:

enter image description here

Leave a Reply