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 != (" ") && 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 != " "
&& 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 != (" ");
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 !=(" ") &&
varExpectedDate < varTodayDate &&
(Approved1==Yes||Approved2==yes))
Related
I have condition, where are no ( ) brackets inside coded by programmer... How can I bracket such ugly coded correctly?
if( c_1 && c_2 || c_3 || c_4 && c_5 || c_6 && c_7 || c_8 || c_9 && c_10)
&& has higher precedence1 in C# than ||. That means your expression is effectively:
if ((c_1 && c_2) || c_3 || (c_4 && c_5) || (c_6 && c_7) || c_8 || (c_9 && c_10))
For further readability, I'd probably extract conditions into local variables with meaningful names. For example:
bool recentlyActive = (c_1 && c_2) || c_3;
bool passwordDisabled = (c_4 && c_5) || (c_6 && c_7);
bool userBanned = c_8 || (c_9 && c_10);
if (recentlyActive || passwordDisabled || userBanned)
{
...
}
1 Precedence in C# is documented in the specification, but it really comes directly out of the grammar. I'm glad of that documentation though, because I wouldn't want to have to read the grammar every time I wanted to understand how operators bind...
I'm having difficulty with a multiple option if statement.
Version 1 matches all without considering the && .contains("up")
if (
|| drow["ifName"].ToString().ToLower().Contains("vlan")
|| drow["ifName"].ToString().ToLower().Contains("st0")
|| drow["ifName"].ToString().ToLower().Contains("ge-0")
&& drow["ifStatus"].ToString().ToLower().Contains("up")
)
Version 2 matches none.
if ( (
|| drow["ifName"].ToString().ToLower().Contains("vlan")
|| drow["ifName"].ToString().ToLower().Contains("st0")
|| drow["ifName"].ToString().ToLower().Contains("ge-0")
)
&& drow["ifStatus"].ToString().ToLower().Contains("up")
Something I am missing?
Table looks basically like
ifName | ifStatus
vlan.0 | up
st0.1 | up
pp0.0 | up
ge-0/0/0 | down
EDIT:
So the goal is to match only rows that have ifStatus = UP, also changed table to clarify a real example.
What is your intended parse? logical OR (||) and logical AND (&&) are both left-associative and have different operator precedences:
http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx
Logical AND binds more tightly than does logical OR, so, an expression like
A || B || C && D
parses as if it were written
A || B || ( C && D )
If that is your intent, you're good. If not, you'll need to add parentheses as needed to get the desired parse. My suspicion is that your intended parse is more like:
(A || B || C ) && D
But that is not how your original test parses.
As a good general rule, if you're mixing ANDs and ORs in a logical expression, always use parentheses to indicate your intent. Misunderstanding operator precedence in logical expressions is a major source of bugs.
This may not fix your problem, but it should make it easier to see what you're doing, as well as make the list more maintainable:
var matchNames = new[] {"a", "b", "c", "vlan.10"};
if (drow["ifStatus"].ToString().ToLower().Contains("up") //check up first, because it's cheaper
&& matchNames.Any(m => drow["ifName"].ToString().ToLower().Contains(m) )
{
//...
}
You can use linq to do this, for sample, add this namespace:
using System.Linq;
and try this:
string[] items = new[] { "vlan.10", "a", "b", "c" };
if (drop["IfStatus"].ToString().IndexIf("up", StringComparison.OrdinalIgnoreCase) > -1 &&
items.Any(x => drop["IfName"].ToString().IndexOf(x, StringComparison.OrdinalIgnoreCase) > -1)
{
// true...
}
Read about the Turkey Test, it shows why is important using the IgnoreCase method to compare instead Contains.
Using a regex here can simplify the logic.
if((Regex.IsMatch(drow["ifName"].ToString().ToLower(), "[abc]"))
&& (Regex.IsMatch(drow["ifStatus"].ToString().ToLower(), "up")))
{
}
in first case: it produce true if any one of the expression (OR Expression or AND Expression)evaluates to true.
Note : it is similar to if(A || B || C || D && E)
so if any OR Expressionin (A,B,C) evalutes to true or Expression D and E evaluates to true it becomes true.
in second case : it produce true if any one of the OR expressions is true and AND Expression drow["ifStatus"].ToString().ToLower().Contains("up") also must be true as you are using parenthesis pair.
Note : it is similar to if( (A || B || C || D) && (E) )
so if any one of the OR Expression(A,B,C,D) should evaluate to true and also AND expression E must be true to produce the result true.
Try This:
String name=drow["ifName"].ToString().ToLower();
Sting status=drow["ifStatus"].ToString().ToLower();
if ( (name.Contains("vlan.10") || name.Contains("a") || name.Contains("b")
|| name.Contains("c")) && (status.Contains("up")))
I'm sorry to ask such an easy question.. I just need some clarifications, because sometimes I mix the differences up.
Can somebody please help me by explaining the difference between the following if statements?
sending = true;
if (sending && e.AssetType == AssetType.Notecard) //#1
vs.
if ((sending) && (e.AssetType == AssetType.Notecard)) //#2
vs.
if (sending || e.AssetType == AssetType.Notecard) //#3
vs.
if ((sending) || (e.AssetType == AssetType.Notecard)) //#4
In this specific case, I need it to evaluate to something like:
"If(sending == true AND e.AssetType == AssetType.Notecard)"
In an other case I need the if statement to check one string and contents of a list like:
"If(string == "Name" OR List.Contains("string"))
The first and the second statements are the same (parenthesis are not obligatory in this case, because of C# evaluation priorities!)
if (sending && e.AssetType == AssetType.Notecard)
if ((sending) && (e.AssetType == AssetType.Notecard))
just as:
if ((sending == true) && e.AssetType == AssetType.Notecard))
if ((sending) && (e.AssetType == AssetType.Notecard))
Also the 3° and the 4° statement will give the same result, for the same reason mentioned above: http://msdn.microsoft.com/en-us/library/6a71f45d.aspx
I would use these statements:
if (sending && (e.AssetType == AssetType.Notecard))
and:
if ((string == "Name") || List.Contains("string"))
(but please take care of string comparison modes, such as upper/lower cases and cultures:
String.Compare(string, "Name", StringComparison.CurrentCultureIgnoreCase) == 0
compares strings without regard of the case and with the current culture)
There is no any difference in those codes.
if ((sending) && (e.AssetType == AssetType.Notecard)) and if (sending && e.AssetType == AssetType.Notecard) evaluates into the same thing.
if(sending == true) or if(sending) is the same thing too.
If you're asking about difference between || and &&:
|| is a LOGICAL-OR. It's enough that only one condition would be TRUE to pass if
&& is a LOGICAL-AND. All conditions must be TRUE in order to pass if
In both cases the evaluation will be done from the left to right.
Example of sequence:
if ((sending) && (e.AssetType == AssetType.Notecard)) => if sending==true AND ..rest..
For the first and second statements produce the same result and for the third and fourth statements also produce the same result.
A couple of things to clarify:
In this case, parentheses are not required and it is just extra code.
When you use Logical-AND operation, the first part is always evaluated, and the second part will only be evaluated if the first part is true.
When you use Logical-OR operation, both parts are always evaluated.
When you have more than +2 expressions, then use parentheses to clarify your intentions. e.g. if(A && B || C) is the same as if((A && B) || C) because the Operators Precedence. but if you want the logical-OR operation to be execute first, then you must use parentheses to override the precedence if(A && (B || C))
Furthermore, if(A && B == C) is the same as if(A && (B == C)) because Equality operation has higher precedence than logical-AND
I'm simply trying to check that one of the three radio boxes has been checked, for some reason even when in debug console all boxes '.Selected = false' it is still skipping over my error message. Any help is appreciated.
if ((rdoIndoor.Checked = false ) && ( rdoOut.Checked = false ) && ( rdoSwimming.Checked = false ))
{
MessageBox.Show("Please select an event style");
}
You are using an assignment operator instead of a comparison operator. The = operator is for assignment. Use == for comparison.
Better yet, get rid of your == operator altogether, and use the ! operator, like this:
if ( !rdoIndoor.Checked && !rdoOut.Checked && !rdoSwimming.Checked )
{
MessageBox.Show( "Please select an event style" );
}
The equality operator, used to compare values, is ==
So your code should be:
if ((rdoIndoor.Checked == false ) &&
( rdoOut.Checked == false ) &&
( rdoSwimming.Checked == false ))
......
use double equals signs (rdoIndoor.Checked **==** false) etc
Single '=' means assignment, i. e. from now let 'rdoIndoor.Checked' be false.
Double '==' is logical test.
You probably know that ;)
I don't know if it is just me being thick but I have a bit of validation code to check for a yes or no answer.
I can't seem to get it to work I have used the code in other places in my program and it works but I can't spot the error if there is one. The code runs through the while anyway no mater what the input character is.
string correctDestenation = Console.ReadLine().ToLower();
while (correctDestenation != "y" || correctDestenation != "n")
{
Console.WriteLine(
"Oops! You must enter a 'y' for yes and a 'n' for no");
correctDestenation = Console.ReadLine().ToLower();
}
Your logic is incorrect. You want to use && instead of ||.
while (correctDestenation != "y" && correctDestenation != "n")
or, you can use De Morgan's Law and look at it the other way, which is equivalent:
while (!(correctDestenation == "y" || correctDestenation == "n"))
That condition will always be satisfied, as a character will not be equal to 'y' or equal to 'n'. Use && instead of ||.
How about you use the AND operator
while (correctDestenation != "y" && correctDestenation != "n")
{
Console.WriteLine("Oops! You must enter a 'y' for yes and a 'n' for no");
correctDestenation = Console.ReadLine().ToLower();
}