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:
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?
CodePudding user response:
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(),
};
}
CodePudding user response:
You can use the var pattern to accomplish something similar.
Try this:
public bool UsePatternMatching(string value)
{
var DoSomething = () => true;
return value switch
{
var str when str.Equals("SomeValue") => DoSomething(),
_ => throw new ArgumentException(),
};
}