0

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;
}
14
  • Are you looking for Enum.IsDefined? Commented Sep 1, 2022 at 8:41
  • Why not check the string first in an if block` then you only switch on the enum after that? Commented Sep 1, 2022 at 8:41
  • Or use only if/else statement to make it more uniform. Commented Sep 1, 2022 at 8:42
  • @DiplomacyNotWar I don't think so unless that can check all values, which I can't seem to see an example of it doing. Commented Sep 1, 2022 at 8:45
  • 1
    If it works, then don't change it. Leave it like it is now, it's readable and simple. Commented Sep 1, 2022 at 9:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Per your suggestion I've used Enum.IsDefined within the if and it works! Only seems to moan if I try to use it within a case. I did have to keep the switch within the else though as in reality there's 70 lines of code in there and I don't want to interfere with it too much (scared of breaking stuff).

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.