Home > Mobile >  Switch all values in enum
Switch all values in enum

Time:09-02

I have an enum and a string, if the string is a certain value I don't care what the enum is as all options are valid. Is there a way to switch all enum values and use when on the string? The best I could come up with is an if statement before the switch;

if (action == ApiParameterConstants.ActionReturn)
{
    return ApiConstants.HomeDeliveryOrderReturnEndpoint;
}
else
{
    switch (orderType)
    {
        case OrderType.HomeDelivery when action == ApiParameterConstants.ActionAccept:
        case OrderType.DoorToDoor when action == ApiParameterConstants.ActionAccept:
                    return ApiConstants.HomeDeliveryOrderAcceptEndpoint;
        ...
        default:
            return string.Empty;
    }
}

Example of what I'm after (I know .All isn't a real thing but you get the idea);

switch (orderType)
{
    case OrderType.All when action == ApiParameterConstants.ActionReturn:
        return ApiConstants.HomeDeliveryOrderReturnEndpoint;
    ...
    default:
        return string.Empty;
}

CodePudding user response:

It sounds like you want Enum.IsDefined to check the value held by orderType is a valid enum value:

if (action == ApiParameterConstants.ActionReturn)
{
    return ApiConstants.HomeDeliveryOrderReturnEndpoint;
}
else if (action == ApiParameterConstants.ActionAccept 
          && Enum.IsDefined(typeof(OrderType), orderType))
{
    return ApiConstants.HomeDeliveryOrderAcceptEndpoint;
}
else
{
    return string.Empty;
}

I've removed the switch and moved the check to the else if, and then moved the default action to the else.

  • Related