Home > Software engineering >  Get object type from enum value
Get object type from enum value

Time:11-11

I have an enum defined wich stores multiple class names. Is there a way I can get the the type of an object given the enum value? The method GetObjectType when called with parameter Types.A should return the type of class A, how should it's body look like?

    public class A
    {

    }

    public class B
    {

    }

    public enum Types
    {
        A = 1,
        B = 2
    }

    public Type GetObjectType(Types type)
    {
         
    }

CodePudding user response:

One simple approach is to use an explicit switch statement.

public Type GetObjectType(Types type)
{
    switch (type)
    {
        case Types.A:
            return typeof(A);
        case Types.B:
            return typeof(B);
    }

    throw new InvalidEnumArgumentException(nameof(type), (int)type, typeof(Types));
}

You just mustn't forget to add to the switch statement when a new enum value is added.


Another approach would be to get the type based on the name of the enum directly.

public Type GetObjectType(Types type)
{
    // Check valid enum
    if (!Enum.IsDefined(typeof(Types), type))
    {
        throw new InvalidEnumArgumentException(nameof(type), (int)type, typeof(Types));
    }

    // Build class name from Enum name. Use your correct namespace here
    string className = "WindowsFormsApp1."   Enum.GetName(typeof(Types), type);

    // Get type from class name
    return Type.GetType(className, throwOnError: true);
}
  • Related