Link to home
Start Free TrialLog in
Avatar of sbornstein2
sbornstein2

asked on

Using IF and OR statement C#

How do I use an OR statement?  I am trying to say IF this or this then do this.  Here is what I have not working with the ||.

if (cboEstimateStage.DataTextFormatString == "Lockdown") || (cboEstimateStage.DataTextFormatString == "Post-Reconfirmation")
{
}
Avatar of fruhj
fruhj

Hi sbornstein2,

  I think you have it right.
  you might want to surround the whole thing with an extra ()
  if
  (
      (cboEstimateStage.DataTextFormatString == "Lockdown") || (cboEstimateStage.DataTextFormatString == "Post-Reconfirmation")
  )
{
}
But I don't think it should be necessary
 

- Jack
ASKER CERTIFIED SOLUTION
Avatar of dungla
dungla
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Anandhi K

The total if condition should be given in one paranthesis
The code is
if ((cboEstimateStage.DataTextFormatString == "Lockdown") || (cboEstimateStage.DataTextFormatString == "Post-Reconfirmation"))
{
}

or

if (cboEstimateStage.DataTextFormatString == "Lockdown" || cboEstimateStage.DataTextFormatString == "Post-Reconfirmation")
{
}
Also know the difference between using one pipe (|) and two pipes(||).  

When using one pipe, buth sides are evaluated before determining if one of them is true.  This is equivalent tothe VB Or command.

With two pipes (called a short-circuit OR) the second operand is evaluated only if necessary (i.e. only if the first operand is false).  This is equivalent to the VB OrElse operator (new to VB.NET).

The difference can be tricky if you have expressions or operations in the second operand that you expect to run each time.  For example:

if ( debitAccount(100) || debitAccount(500) )
{
 ...
}

Suppose debitAccount is a function that debits a bank account and returns true if the acount still has funds left, otherwise returns false, the second call will not be called if the first call returns true.  

On the other hand,

if (array == null || array.Length == 0)
{
  ...
}

This will always work because if the array is null, the first operand will be true and the short-circuit will not process the second operand.  With a single pipe, the second operate could be evaluated and result in a NullReferenceException.
if you are used to put each condition in parentesis, you need to put a parentesis around the whole thing
(() || ())

or you can do just

(this || that)

if (cboEstimateStage.DataTextFormatString == "Lockdown" || cboEstimateStage.DataTextFormatString == "Post-Reconfirmation")
{
}