1

I have an enum defined which 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)
    {
         
    }
3
  • What if I do GetObjectType( (Types)0 )? Commented Nov 10, 2021 at 17:58
  • 1
    Type.GetType or an explicit switch statement Commented Nov 10, 2021 at 17:59
  • According to learn.microsoft.com/en-us/dotnet/csharp/language-reference/… , An enum declaration that does not explicitly declare an underlying type has an underlying type of int . Therefore, it's unnecessary to get the type for A or B (within the enum), because we already know that the type is int. Also, the A and B that you've declared inside the enum, have nothing to do with the classes that you've defined. Commented Nov 10, 2021 at 18:03

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I recommend using ExhaustiveMatching from NuGet. It will give you a handy compile-time error if you don’t have exhaustive switch statements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.