Trying to pass an unknown enum type

I’m trying to pass around an unknown enum type which is set by switch cases then automatically generate arrays from them. Given that the following, which I use in other areas of code, works:

subType = new EquipmentSubTypeList[Enum.GetNames(typeof(EQUIPMENTTYPE)).Length];

I tried the following which doesn’t:

Type enumType;

        switch (equipmentType)
        {
            case EQUIPMENTTYPE.Weapon:
                enumType = typeof(WEAPONTYPE);
                break;
        }

        if (subType == null || subType.Length < 1)
        {
            subType = new EquipmentSubTypeList[Enum.GetNames(enumType).Length];
        }

GetNames(enumType) is where I am getting the error in VS. I can’t figure out why this isn’t working. Any help with why it doesn’t and any advice for achieving what I am trying to would be greatly appreciated.

What is the error you are getting? That enumType is uninitialized? If equipmentType is not EQUIPMENTTYPE.Weapon then you never set enumType before using it.

You’re right, I’m an idiot, the error is being thrown because there’s no default case and it could theoretically be unassigned by the time it gets there even though in practice it couldn’t possibly be (i trimmed away all the other cases to avoid bloating the snippet). Guess I can solve that by wrapping the if in another if to make sure it’s an enum type to get rid of the error. Thanks!

When you switch on an enum, you should always have a “default” case. Someone could come along and add new values to the enum. Someone could even cast an integer into your enum type to get a value that doesn’t correspond to any of your named values.

It’s possible the default case will just throw an exception, but you should have one.

1 Like