Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c# is there such an operator to mean 'AndAlso' with reference to the first variable?

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,

like image 889
N0xus Avatar asked Oct 02 '22 16:10

N0xus


2 Answers

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:

  1. No other language (that I know of) has one, as such it's probably not all that useful
  2. All features starts with -100 points, and needs good justification why it needs to be raised above the threshold needed to actually implement it, and will also have to justify doing it before or instead of other features. Since it's so easy to write the expression anyway I doubt it meets all these criteria.

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 <=.

like image 82
Lasse V. Karlsen Avatar answered Oct 12 '22 10:10

Lasse V. Karlsen


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;
}
like image 21
MUG4N Avatar answered Oct 12 '22 11:10

MUG4N