Miguel Moura
Miguel Moura

Reputation: 39474

Negate value on condition?

I have the following:

public Boolean Test(Boolean value, Boolean negation) {
  return negation ? !value : value;
}

So value is negated only if negated is true. Otherwise value is returned either it is true or false.

Is there any operator to do this as an alternative of what I am doing?

Upvotes: 0

Views: 838

Answers (1)

poke
poke

Reputation: 388023

To find an operator for boolean operations, you should consider creating a truth table to see all the possible outcomes. In your case, there are two inputs value (V) and negation (N):

N V | Result
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 0

As you can see, you return true only one of N and V are true. That’s an exclusive or.

In C#, that’s the operator ^ (xor), so you can just write your function like this:

public bool Test(bool value, bool negation)
{
    return negation ^ value;
}

Upvotes: 9

Related Questions