Logical AND (&&) in an If Statement

  • Thread starter Thread starter Charles Law
  • Start date Start date
C

Charles Law

This is a very basic question, but I can' turn up a statement on the
subject:

In C#, if I have

If (x == 1 && y == 2)
{
....
}

Suppose x is not equal to 1, does the logical test for y == 2 still get
executed?

TIA

Charles
 
No; the && and || operators are short-circuited:

* if the first operand in a && is false, then false is returned
without looking at the second operand
* if the first operand in a || is true, then true is returned without
looking at the second operand

Marc
 
Thanks Leo and Marc for the replies.

What was concerning me was that in the following:

const int expectedlength = 10;

byte[] myarray;

// assign to myarray
...

If (myarray.GetLength(0) == expectedlength && myarray[expectedlength -
1] == 0x1)
{
...
}

If the array was not the expected length then the subsequent test could
cause an IndexOutOfRange exception.

Charles
 
This is a very basic question, but I can' turn up a statement on the
subject:

In C#, if I have

If (x == 1 && y == 2)
{
...

}

Suppose x is not equal to 1, does the logical test for y == 2 still get
executed?

TIA

Charles

If you have any VB.NET experiance, the && and || operators are
equivalent to the VB.NET AndAlso and OrElse operators.
 
Thanks Leo and Marc for the replies.

What was concerning me was that in the following:

const int expectedlength = 10;

byte[] myarray;

// assign to myarray
...

If (myarray.GetLength(0) == expectedlength && myarray[expectedlength -
1] == 0x1)
{
...
}

If the array was not the expected length then the subsequent test could
cause an IndexOutOfRange exception.

No, that should be fine. I'd use the Length property instead of
GetLength(0) though, just for the sake of readability.

Jon
 
Hi Jon

Thanks for the confirmation; and noted about the Length suggestion.

Cheers

Charles


Jon Skeet said:
Thanks Leo and Marc for the replies.

What was concerning me was that in the following:

const int expectedlength = 10;

byte[] myarray;

// assign to myarray
...

If (myarray.GetLength(0) == expectedlength &&
myarray[expectedlength -
1] == 0x1)
{
...
}

If the array was not the expected length then the subsequent test could
cause an IndexOutOfRange exception.

No, that should be fine. I'd use the Length property instead of
GetLength(0) though, just for the sake of readability.

Jon
 
Hi Zacks
If you have any VB.NET experiance, the && and || operators are
equivalent to the VB.NET AndAlso and OrElse operators.

I have, as I generally use VB.NET, so that makes sense to me.

Thanks.

Charles


This is a very basic question, but I can' turn up a statement on the
subject:

In C#, if I have

If (x == 1 && y == 2)
{
...

}

Suppose x is not equal to 1, does the logical test for y == 2 still get
executed?

TIA

Charles

If you have any VB.NET experiance, the && and || operators are
equivalent to the VB.NET AndAlso and OrElse operators.
 
Back
Top