1

What syntax exists in C# to help with multiple condition testing?

I often have to test for multiple conditions in the following manner:

if (a == 3 || a == 4)

Perhaps I'm being subjective, but that isn't very pretty.

If there is a larger set of conditions, I could do:

if (new int[]{3, 4, 5, 6, 7}.Contains(a))

But if there are just a few conditions to test, I'm not saving any keystrokes.

Is there a syntax shortcut in the C# language that would allow me to accomplish something like the following, without many keystrokes and without extension methods, etc?

// doesn't work
if (a == 3 || 4)

This is different from this SO thread, because it is dealing with short conditions (2 or 3), all with an unchanging "a" value in an "a compare to b" comparison.

Aaron Thomas
  • 5,054
  • 8
  • 43
  • 89
  • "I'm not saving any keystrokes" - saving keystrokes is never a good aim. Making things more readable or (after validating that it's sensitive) more performant are good aims. – Jon Skeet Jul 05 '16 at 16:53
  • @Shachaf.Gortler thank you, edited to explain difference with other SO question you referenced. – Aaron Thomas Jul 05 '16 at 16:53
  • So you're *really* asking for a language feature *just* for the case where you have a single variable you want to compare only against a small number of cases? That's way, way below the language feature bar, IMO. – Jon Skeet Jul 05 '16 at 16:54
  • @JonSkeet you are correct. I think the real issue however is not just keystrokes saved, but that one side of the condition never changes, however I must repeat it again, every time I want to compare to the other side which does change. – Aaron Thomas Jul 05 '16 at 16:54
  • 3
    You could write your own extension method such as a.IsAny(3, 4) to simplify your code. – Marko Jul 05 '16 at 16:54
  • Just how often do you want this? Perhaps you should use a `switch` statement instead, if there are several such pairs? – Jon Skeet Jul 05 '16 at 16:58
  • @JonSkeet I think I'm outside the realm of the question now, but personally I would use such a feature a good percentage of the time that `||` or `&&` exists in an `if` statement. "if a is this, that, or the other" would be better than "if a is this, or a is that, or a is the other" - especially if "this, that, or the other" is the same type as `a`, and `a` isn't changing during the course of the `if` statement. – Aaron Thomas Jul 05 '16 at 17:04
  • Whereas I rarely find myself in that situation. It sounds like an extension method would indeed help you. – Jon Skeet Jul 05 '16 at 17:05
  • I second what Marko and JonSkeet have said. Use an extension method. – GreatAndPowerfulOz Jul 05 '16 at 17:08
  • Thank you all. For future reference, using generics in an extension method fits this sort of application very well, as laid out in http://stackoverflow.com/a/14067242/2658159. – Aaron Thomas Jul 05 '16 at 17:14

1 Answers1

0

No there is not. Sorry, but this is your answer.

nvoigt
  • 75,013
  • 26
  • 93
  • 142