switch (true)
isn't a "thing" in C# like it's VB counterpart (Select True
) . And even if it was, I'd strongly recommend avoiding it.
When you write a switch
statement in C#, the cases must either be a constant or a pattern match. If you are insistent on using a switch
, you can use the following (which only works on C# 7+)
switch (header)
{
case var _ when header.Contains("foo"):
return true:
case var _ when header.Contains("bar"):
return false:
default:
throw new Exception();
}
In this case, var _
is the object pattern (which will match anything non-null) along with a discard since we want to operate on the other variable. Don't like the discard? You could do this as well:
switch (header)
{
case var h1 when h1.Contains("foo"):
return true:
case var h2 when h2.Contains("bar"):
return false:
default:
throw new Exception();
}
That said, don't use a switch for this. A chain of if/else is much more clear. Anyone reading your code (including your future self) will thank you for it.
if (header.Contains("foo"))
return true;
if (header.Contains("bar"))
return false;
// etc