Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading