I’ve debated before the usefulness of the | and & operators. The use of the | operator depends on the context in which it is used.

In the case of bools a boolean operation is performed. In the case of ints a bitwise OR is performed.

For boolean operations when the | operator is used both sides of the operator are evaluated. In the example below both VerifyStatus and SetDefaults are called regardless of the boolean returned by each of them.

public void TestTransaction(PaymentTransaction Transaction)
{
    if (Transaction != null && 
        (VerifyStatus(Transaction.State) | SetDefaults(Transaction)))
    {
        //do something with the code
    }
}
private bool VerifyStatus(ItemState State)
{
    if (State == null)
        return false;
    if (State.Status == Status.NotVerified)
        ValidateStatus(State);
    if (State.Status == Status.Valid)
        return true;
    //Status.Invalid
    return false;
}
private void ValidateStatus(ItemState State)
{
    //validate the status
}
private bool SetDefaults(PaymentTransaction Transaction)
{
    if (Transaction == null)
        return false;
    //no need to set the defaults if the state is already valid
    if (Transaction.State.Status == Status.Valid)
        return true;
    //set all the default values for the transaction
    return true;
}

Ok, I know it’s not a pillar of phenomenal code. But you get the point, both of the sides of the | are run. Now, what if you’ve all ready evaluated the status earlier in code? No need to do it again. But you may need to still set the defaults. Well, that is where the |= comes into play.

bool transStatus = VerifyStatus(Transaction.State);
//do something with the code
transStatus |= SetDefaults(Transaction);
if(transStatus)
{
    //do something with the code
}

In the case of an int a bitwise operation is performed.

int a = 0x0c;
a = a | 0x06;
//a results in 0x0000000e
//1100
//0110 results in
//1110 which is e

Like the logical operation example above the | and assignment can be collapsed down to:

int a = 0x0c;
a |= 0x06;

I think it’s very important to understand the difference between | and || as well as & and &&. Recently I came across a bunch of code where the original developer used | and || interchangeably. They are not the same. Using | in place of || overrides the fail fast nature of boolean operations most modern languages support. They are not interchangeable. If Transaction was null the following code would not work

if(Transaction == null | Transaction.State == null)

simply because both sides of the operation are evaluated so Transaction.State would throw a null pointer exception. Not only that but your code will run slower.

Next in this series will be checked and unchecked.

Later,
Brian

Leave a Reply

Your email address will not be published. Required fields are marked *

FormatException

928 East Plymouth Drive Asbury Park, NJ 07712