Skip to main content

How to get switch case values [Resolved]

I was wondering if there is a way to get the values of every case in a switch statement? When you provide a not implemented case, I would like to throw some exception and provide a list of available case values.

switch (partName.Trim().ToLower())
{
    case "engine":
        //something
        break;
    case "door":
        //something
        break;
    case "wheel":
        //something
        break;
    default:
        throw new NotImplementedException($"Available parts are {????}.");
}

Question Credit: Lubomir Stoimchev
Question Reference
Asked January 11, 2019
Posted Under: Programming
41 views
1 Answers

Short answer: no. There is no way of doing this programmatically.

Longer answer: you can work around this with an enum, eg

public enum Parts { engine, door, wheel }

...

if (Enum.TryParse(partName, out var part))
{
    switch (part)
    {
        case Parts.engine:
            //something
            break;
        case Parts.door:
            //something
            break;
        case Parts.wheel:
            //something
            break;
    }
}
else
{
    var listOfValues = string.Join(", ", Enum.GetNames(typeof(Parts)));
    throw new NotImplementedException($"Available parts are {listOfValues}.");
}

credit: David Arno
Answered January 11, 2019
Your Answer