Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In C#, How To Perform Pattern Matching With Switch For Non-Constant String Value?

In C#, How To Perform Pattern Matching With Switch For Non-Constant String Value?

I’d like to be able to use non-constant string variables as the match target in a switch statement.

I have the code below, but I’m encountering error CS0150: A constant value is expected at case expectedValue:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public bool UseStandardSwitch(string inputValue)
{
    var expectedValue = "SomeValue";

    bool result = default;
    var DoSomething = () => { result = true; };
            
    switch (inputValue)
    {
        case expectedValue:
            DoSomething();
            break;
        default:
            break;
    }
    return result;
}

Is there a way to achieve a similar result?

>Solution :

No need to introduce a variable (as in your answer) – you can use discard with case guard:

public bool UseStandardSwitch(string inputValue)
{
    var expectedValue = Console.ReadLine()!;
    Func<bool> DoSomething = () => true;
    
    return inputValue switch
    {
        _ when inputValue.Equals(expectedValue) => DoSomething(),
        _ when inputValue.Equals(expectedValue + "1") => DoSomething(),
        _ => throw new ArgumentException(),
    };
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading