简体   繁体   中英

How to use multiple conditional operators using C#

I want to use combination of the 2 operators: the && and the || operator using C#. I have 5 variables that I would like to make sure if these conditions are met. varRequestedDate varTotdayDate varExpectedDate Approval1 Approval2 Here is what I have for my current condition but would like to add other variables adding the OR operator:

if (varRequestedDate != ("&nbsp;") && varExpectedDate < varTotdayDate)

here is the pseudocode for what I would like to see after the updated version:

(if varRequestedDate is not blank 
and varExpectedDate is less than varTotdayDate
and either Approved1 OR Approved2 = Yes)
send email()

i cannot figure out how to do this. thanks

You just have to add nested parentheses:

if (varRequestedDate != "&nbsp;" 
    && varExpectedDate < varTotdayDate
    && (Approved1 == "Yes" || Approved2 == "Yes")
)
    sendEmail();

For the sake of readability and expressiveness I would extract the boolean values into meaningfully named variables:

var isDateRequested = varRequestedDate != ("&nbsp;");
var isDateWithinRange = varExpectedDate < varTotdayDate;
var isApproved = Approved1 == "Yes" || Approved2 == "Yes";

if (isDateRequested && isDateWithinRange && isApproved)
{...}

You can nest logical operators using parentheses (just like arithmetic operators). Otherwise they follow a defined precedence going left to right.

if (
    varRequestedDate !=("&nbsp;") && 
    varExpectedDate < varTodayDate && 
    (Approved1==Yes||Approved2==yes))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM