0

Is there a short hand method for handling a two comparisons in a conditional statement?

For example:

if(ReturnedCount > 0 && ReturnedCount < 50)
{
    ...
}

I'm fairly certain that a variable must always be on the left hand side of an operator because when I tried the following it didn't work:

if(0 < ReturnedCount < 50)
{
    ...
}

I did a search on google for the c# equivalent of the between keyword in SQL and got no good results.

Is there a better way to handle this sort of double comparison for the same variable?

W.Harr
  • 303
  • 1
  • 4
  • 15
  • 3
    Not really, you could write a function called `bool IsBetween(value, min, max)`, but you can't short-hand it the way you are doing it. – Ron Beyer May 10 '18 at 18:48
  • You can only evaluate two sides with that operator, so there is no way around explicitly saying `(variable > 0 && variable < 50)` – maccettura May 10 '18 at 18:50
  • 1
    In this link, there are certain answers which may be helpful for you. https://stackoverflow.com/questions/3188672/how-to-elegantly-check-if-a-number-is-within-a-range – Arpit Gupta May 10 '18 at 18:54
  • @ArpitGupta as long as the number one answer is not used (Enumerable.Range()), because that is a _horrible_ answer – maccettura May 10 '18 at 18:59
  • 1
    @maccettura Agree, just in case, OP finds something useful. – Arpit Gupta May 10 '18 at 19:06

1 Answers1

2

Short answer, C# doesn't have any syntax sugar to help, each conditional test just gets added on to the statement.

At some point, when it starts getting hard to read, you can break it out into a method call that returns true/false.

ie.

if (Pred.Equals( a, b, c, d ))
{ ... }

Where, Pred is a (non existant) static class containing helper methods to be used as logical predicates.

Alternately...

A second approach to this is chaining method calls to represent consecutive conditional tests.

ie.

if (a.GreaterThan(b).LessThan(c).IsTrue())
{...}

Where, GreaterThan and LessThan are extension methods which return either the 'this' value or 'null', and IsTrue returns true if 'this' is non-null.

Those are the only two techniques I've come across myself, goodluck!

James
  • 1,973
  • 1
  • 18
  • 32
  • Thanks for your answer. The second method especially, I find useful for verifying multiple conditions when the number of conditions doesn't merit building helper methods to process them. At the same time, I find it easier to read than if you spelling out each condition itself. – W.Harr May 10 '18 at 20:08