Shaiju Janardhanan
Shaiju Janardhanan

Reputation: 564

Is it ok to use bitwise operator in place of a logical operator like OR

This may be stupid.but i have a simple doubt Suppose i have the following check in a function

bool Validate(string a , string b)
{
    if(a == null || b == null)
    {
        throw new NullReferenceException();
    }
    else
    {
    }
}

Is it ok to use bitwise OR for validation as shown below

if(a == null | b == null)

Upvotes: 1

Views: 370

Answers (4)

anaximander
anaximander

Reputation: 7140

This should work, because when used on things that evaluate to bool, the "bitwise" operators carry out logical operations just the same. You might find it less efficient, though. The logical operators in C# will short-circuit, meaning they'll skip evaluation of the second expression if the answer can be deduced from the first. So in your example, if a == null turns out to be true, then || would return true immediately, while | would go ahead and check b == null anyway.

Upvotes: 1

Honza Brestan
Honza Brestan

Reputation: 10957

In this case (with bool arguments) the | operator is not a bitwise operator. It's just a non-short-circuiting version of the logical or(||).

The same goes for & vs. && - it's just a non-short-circuiting version of logical and.

The difference can be seen with side-effects, for example in

bool Check()
{
    Console.WriteLine("Evaluated!");
    return true;
}

// Short-circuits, only evaluates the left argument.
if (Check() || Check()) { ... }

// vs.

// No short circuit, evaluates both.
if (Check() | Check()) { ... }

Upvotes: 1

ne1410s
ne1410s

Reputation: 7102

As has been commented upon, the code is indeed 'ok'.

Using the single pipe '|' will evaluate all expressions before returning the result. '||' can be more efficient, since it ceases as soon as an expression evaluates to true.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063774

In boolean expressions (rather than integers etc), the main difference is: short-circuiting. || short-circuits. | does not. In most cases you want short-circuiting, so || is much much more common. In your case, it won't matter, so || should probably be used as the more expected choice.

The times it matters is:

if(politics.IsCeasefire() | army.LaunchTheRockets()) {
    // ...
}

vs:

if(politics.IsCeasefire() || army.LaunchTheRockets()) {
    // ...
}

The first always does both (assuming there isn't an exception thrown); the second doesn't launch the rockets if a ceasefire was called.

Upvotes: 10

Related Questions