I'm curious to know if there is such an operator that will allow for the following
Initial line:
if(foo > 1 && foo < 10)
Desired Line: (Variable repetition assumption?)
if(foo > 1 && < 10)
Im looking to educate myself a little on how these operators work at a lower level, explanation as to why not would be much appreciated.
Thanks,
No, there is no such operator in C#. You will have to repeat the variable or expression to compare against.
I don't know the official reason why such an operator does not exist in C# but here's a few thoughts:
You could (although I don't think this would be a good idea) create an extension method:
void Main()
{
int foo = 5;
if (foo.Between(1, 10))
Debug.WriteLine("> 1 and < 10");
else
Debug.WriteLine("?");
}
public static class Extensions
{
public static bool Between<T>(this T value, T lowNotIncluded, T highNotIncluded)
where T : struct, IComparable<T>
{
return value.CompareTo(lowNotIncluded) > 0 && value.CompareTo(highNotIncluded) < 0;
}
}
But would not recommend that. One question to raise if you want to go the extension method route is how to handle all the combinations of >
, >=
, <
, and <=
.
This type of operator does not exist in C#. But I wouldn't use it anyway because the readability and intention of your code is not very clear. Instead I would use an extension method like this:
// using extension method
int number = 15;
if (number.IsBetween(0, 12))
{
...
}
// definition of extension method
public static bool IsBetween(this int num, int lower, int upper, bool inclusive = false)
{
return inclusive
? lower <= num && num <= upper
: lower < num && num < upper;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With