Home > front end >  If x or - 2, do something
If x or - 2, do something

Time:12-30

Given int x, I want to be able to check if it has increased or decreased by 2. Is there a clean way to do this using the - condition or should I check both if increased and if decreased separately using or?

Is it possible to make the if statement shorter or do I just have to check multiple conditions at once instead of both at the same time using C#

CodePudding user response:

You can check it using || operator, something like this, here prevX is previous value.

if (x - prevX == 2 || prevX - x == 2) {
  
}

CodePudding user response:

I would do this by storing initial value of variable and then comparing it with actual using Math.Abs method

var initialX = x; // store value of x before modification

// operations on x

if (Math.Abs(initialX - x) == 2)
{
    // x was decreased or increased by 2
}

As long as x is value type, it would be convenient to wrap up operations in separate method and use it like this:

if (Math.Abs(PerformOperations(x) - x) == 2)
{
    // x was decreased or increased by 2
}

But PerformOperations can't take params as reference (with ref keyword).

  • Related