best way to do between check

  • Thread starter Thread starter DBC User
  • Start date Start date
D

DBC User

This is a very simple question, I have a number and I want to check if
the number is between 2 integers. I can use 'if' to resolve this
situation. But I am curious, if there is any other verbs that I can
use in C# like sql 'between'?
Thanks.
 
Nope, an if statement is really what you have to use here (along with an
&& operator to check both conditions). You could use the tertiary switch
statement (e.g. "3 < x && x < 6 ? "between" : "not between") but that's
really the same as an if statement.
 
This is a very simple question, I have a number and I want to check if
the number is between 2 integers. I can use 'if' to resolve this
situation. But I am curious, if there is any other verbs that I can
use in C# like sql 'between'?

No but you can always roll your own function. How about something like this::

public static bool IsInRange<T>(T value, T minValue, T maxValue) where T : IComparable<T>
{
Debug.Assert(minValue.CompareTo(maxValue) <= 0);
if (minValue.CompareTo(maxValue) > 0)
{
string message = string.Format("\"minValue\" ({0}) must be less than or equal to \"maxValue\" ({1})",
minValue.ToString(), maxValue.ToString());
throw new ArgumentException(message);
}

return (value.CompareTo(minValue) >= 0 && value.CompareTo(maxValue) <= 0);
}

bool excellentStudent = IsInRange(grade, 90, 100);
 
No but you can always roll your own function. How about something like this::

public static bool IsInRange<T>(T value, T minValue, T maxValue) where T : IComparable<T>
{
Debug.Assert(minValue.CompareTo(maxValue) <= 0);
if (minValue.CompareTo(maxValue) > 0)
{
string message = string.Format("\"minValue\" ({0}) must be less than or equal to \"maxValue\" ({1})",
minValue.ToString(), maxValue.ToString());
throw new ArgumentException(message);
}

return (value.CompareTo(minValue) >= 0 && value.CompareTo(maxValue) <= 0);

}

bool excellentStudent = IsInRange(grade, 90, 100);

This is a pretty cool stuff.
Thanks.
 
Just to point out a caveat that could bite you on the backside if you're not
careful.

Technically, 'between' does NOT include either of the limits. I.E., 4 and 5
are between 3 and 6 but 3 is NOT between 3 and 6.

However, in everyday useage, between is often considered to include either
of the limits. I.E., 3, 4, 5, and 6 are ALL between 3 and 6. For example,
This is how the between operator is implemented in TRANSACT-SQL

The point is, that to be able to use any 'between' function/operator with
confidence you must be aware of just what that function/operator considers
'between' to mean.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top