I have a datetime definition that I do not know how to use of. What exactly is the expression between the <> signs? it returns Boolean but how?
bool x= DateTime.Now.AddDays(20) <DateTime.Now && DateTime.Now.AddDays(10)> DateTime.Now;
Format it differently and it will be easy to see that it's two less than/greater than signs:
bool x = DateTime.Now.AddDays(20) < DateTime.Now
&& DateTime.Now.AddDays(10) > DateTime.Now;
bool x = DateTime.Now.AddDays(20) < DateTime.Now //(1)
&& DateTime.Now.AddDays(10) > DateTime.Now; //(2)
To English:
(1): Is (Today + 20 days) smaller than Today?
// We have False
(2): Is (Today + 10 days) greater than Today?
// We have True
And Finally (1) && (2) will return your result x
// We have x = True && False = False
What exactly is the expression between the <> signs? it returns Boolean but how?
As already mentioned in the code that you posted < and > and && are operators and not tags
the first < is a "less than" relational operator
the last > is a "greater than" relational operator
These operators compare the operands at each side of the operator and return true or false.
the middle operator && is called The conditional-AND operator and it
performs a logical-AND of its bool operands
This is why the whole statement returns bool
Related
In math, we have -1 * -1 = 1. When 2 negatives multiplies together, we get a positive.
However in C# bool, I am not able to find a way to do so.
int i = -1
int j = -1
bool bi = i>0
bool bj = j>0
Console.writeLine (bi)
Console.writeLine (bj)
Console.writeLine (bi && bj)
result:
false
false
false
obviously, the && is the not the right operator.
Which operator allows me to have 2 Boolean when both are false, returning true
i.e.
Console.Writeline (false false)
result true
The closest to your logic is using negated XOR:
! (bi ^ bj);
This way you'd get something like:
1 * 1 = 1
-1 * 1 = -1
1 * -1 = -1
Also you could use simple comparison operator ==:
bi == bj;
Which operator allows me to have 2 Boolean when both are false,
returning true
If you want to check two values are equal (e.g. both are true or both are false) then == (the equality operator) is your best bet.
var bob = true == true;
var bob2 = false == false;
Both bob and bob2 will be true.
This is perfect for your problem since you want to know if both numbers are negative or both numbers are positive (since in either of those scenarios, multiplying them will result in a positive number).
Console.Writeline(bi == false && bj == false) or for short (!bi && !bj)
This question already has answers here:
C# conditional AND (&&) OR (||) precedence
(6 answers)
Closed 3 years ago.
I'm going through some C# coding exercises and have run into some operator logic that's stumped me.
The following line of code evaluates to false:
int a = 40, int b = 50;
if (a >= 20 && a <= 30 && (b < 20 || b > 30))
{
return a;
}
However, if I remove the brackets from inside the if statement, it evaluates to true.
if (a >= 20 && a <= 30 && b < 20 || b > 30)
{
return a;
}
Can anyone explain what I'm missing? Given that a isn't between 20 and 30, shouldn't it return false? I don't understand why putting the b portion of the if statement in brackets makes it evaluate to false.
Is it evaluating everything prior to "b > 30" as a single condition?
This is all to do with operator precedence.
Just like how * are evaluated first before + (we say * has a higher precedence than +), && is evaluated before ||, as specified.
In the first code snippet, you used brackets to "override" this precedence, making the || part evaluate first, just like how you can add parenthesis to the expression 1 + 2 * 3 to make it evaluate to 9 instead of 7.
a >= 20 && a <= 30 && (b < 20 || b > 30)
^^^^^^^^^^^^^^^^^
this part first
which becomes:
a >= 20 && a <= 30 && true
^^^^^^^ ^^^^^^^
now these parts
which becomes:
false && false && true
resulting in false.
In the second example however, there are no parentheses so the expression is evaluated according to the normal precedence rules:
a >= 20 && a <= 30 && b < 20 || b > 30
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This part first
Which becomes:
false || b > 30
^^^^^^
then this
which becomes:
false || true
resulting in true.
If you look at the second part where you have removed the parenthesis, it is now divided into two subparts.
First one being : a >= 20 && a <= 30 && b < 20 This evaluates to false.
First one being : b > 30 This statement evaluates to true.
So at the end you have something like this
F || T from both the statements which should eventually give you true as end result
I have a (C#) function that checks four sets of conditions and returns a bool. If any of them are true, it returns true. I'm sure I could simplify the logic but I want it to be fairly readable.
The CodeMaid extension in Visual Studios and tells me the cylomatic complexity of the function is 12. I looked it up and the cylomatic complexity is
the number of independent paths through the source code
I don't understand why it's 12. I can think of it two ways, either the cyclomatic complexity should be 2, because it always goes through the same path but could return either a true or a false. Or could understand if it was 16, because the four booleans or'd together at the end could each be true or false, 2*2*2*2 = 16.
Can someone tell me why its 12? Maybe even show a diagram so I can visualize the different paths?
public bool FitsCheckBoxCriteria(TaskClass tasks)
{
// note: bool == true/false comparisons mean you don't have to cast 'bool?' as bool
// if neither checkboxes are checked, show everything
bool showEverything = NoShutDownRequiredCheckBox.IsChecked == false &&
ActiveRequiredCheckBox.IsChecked == false;
// if both are checked, only show active non-shutdown tasks
bool showActiveNonShutdown = ActiveRequiredCheckBox.IsChecked == true &&
tasks.Active == "YES" &&
NoShutDownRequiredCheckBox.IsChecked == true &&
tasks.ShutdownRequired == "NO";
// if active is checked but shudown isn't, display all active
bool showActive = ActiveRequiredCheckBox.IsChecked == true &&
tasks.Active == "YES" &&
NoShutDownRequiredCheckBox.IsChecked == false;
// if non-shutdown is checked but active isn't, display all non-shutdown tasks
bool showNonShutdown = NoShutDownRequiredCheckBox.IsChecked == true &&
tasks.ShutdownRequired == "NO" &&
ActiveRequiredCheckBox.IsChecked == false;
return showEverything || showActiveNonShutdown || showActive || showNonShutdown;
}
Thanks in advance.
Edit:
I changed it to this. assigning local variables for the checkbox conditions didn't have any effect, but creating booleans out of the "YES"/"NO" cranked up the complexity to 14, which I think I understand.
public bool FitsCheckBoxCriteria(LubeTask tasks)
{
bool noShutdownReqChecked = (bool)NoShutDownRequiredCheckBox.IsChecked;
bool activeChecked = (bool)ActiveRequiredCheckBox.IsChecked;
bool active = tasks.Active == "YES" ? true : false;
bool shutdownReq = tasks.ShutdownRequired == "YES" ? true : false;
// if neither checkboxes are checked, show everything
bool showEverything = !noShutdownReqChecked && !activeChecked;
// if both are checked, only show activeChecked non-shutdown tasks
bool showActiveNonShutdown = activeChecked && noShutdownReqChecked && active && !shutdownReq;
// if activeChecked is checked but shudown isn't, display all activeChecked
bool showActive = activeChecked && !noShutdownReqChecked && active;
// if non-shutdown is chceked but activeChecked isn't, display all non-shutdown tasks
bool showNonShutdown = noShutdownReqChecked && !activeChecked && !shutdownReq;
return showEverything || showActiveNonShutdown || showActive || showNonShutdown;
}
The key is in "independent paths".
I'm going to rewrite your code to shorten it so we can discuss it.
public bool FitsCheckBoxCriteria(TaskClass tasks)
{
bool E1 = A1 && A2;
bool E2 = B1 && B2 && B3 && B4;
bool E3 = C1 && C2 && C3;
bool E4 = D1 && D2 && D3;
return E1 || E2 || E3 || E4;
}
The Cyclomatic complexity is the number of independent paths. This is not the total possible number of return values (2).
The && operator and the || operator are short circuit operations; if A1 is false, A2 is not evaluated. Similarly, if E1 is true, E2 is not evaluated.
If you replace all the &&s with & and all the ||s with | in the code above, the cyclomatic complexity is 1, because there is only one path through the code.
(This wouldn't make it better code though).
As it is, there are 72 possible paths...
A1, B1, C1, D1, E1 are evaluated; the others are not.
A1, A2, B1, C1, D1, E1 are evaluated; the others are not.
A1, B1, B2, C1, D1, E1 are evaluated; the others are not.
A1, A2, B1, B2, C1, D1, E1 are evaluated; the others are not.
etc...
But path 4 doesn't contain any new code that isn't already on the previous paths. And this is the definition of "independent paths" - each path must include new code.
So in this example, you can count the code by hand as follows:
1 + the number of short circuit operators in this code (11) = 12.
Wikipedia has an excellent in depth explanation.
This is just a guess, but I think the assignments are +2 each (if =true/else =false) and then +1 for each possible exit condition in the return statement. So it might unwind into something like:
bool showEverything = false;
if (...) { showEverything = true; } +1
else { showEverything = false; } +1
bool showActiveNonShutdown = ... +2 if/else
bool showActive = ... +2 if/else
bool showNonShutdown = ... +2 if/else
if (showEverything) {...} +1
else if (showActiveNonShutdown) {...} +1
else if (showActive) {...} +1
else if (showNonShutdown) {...} +1
else {false}
C# uses short-circuit evaluation which means that if there is an x && y expression y is evaluated only if it is necessary, more precisely, if x is true. This means that result = x && y; has two independent execution paths: (1) if x is false then only x is evaluated and result gets false value (without evaluating y) but (2) if x is true y is evaluated as well and result gets the evaluation result of y. This means that every && and || operator increases the cyclomatic complexity and in the first example there are 8 && and 3 || operators so the cyclomatic complexity of the method is 12.
What is the difference in both of the expressions ? Using brackets or not in this case. What is the difference ?
(!String.IsNullOrEmpty(model.SpouseCitizenType) || !String.IsNullOrEmpty(model.SpouseNomPrenom)) &&
String.IsNullOrEmpty(model.SpouseEGN);
!String.IsNullOrEmpty(model.SpouseCitizenType) || !String.IsNullOrEmpty(model.SpouseNomPrenom) &&
String.IsNullOrEmpty(model.SpouseEGN);
Operator AND && has a higher precendence than OR ||. So, if we denote conditions used here as 1, 2 and 3, first line is equvalent to
(1 || 2) && 3
and the second
1 || (2 && 3)
For the full list of operators sorted in order of precedence check out this MSDN page
I have an if statement as follows
if (1 <= value <= 20)
{
}
value is a double.
however I get an error which says that "Operator '<=' cannot be applied to operands of type 'bool' and 'double'"
Is there a way around this error?
C# doesn't allow you to do this.
Do like this:
if (1 <= value && value <= 20)
The problem is not the double, problem is your syntax is incorrect.
You:
if (1 <= value <= 20)
{
}
That is interpreted as
(1 <= value) <= 20
so first 1 will be compared with value and it will be determined if the former is "less than or equal" the latter. That gives a boolean. Then that boolean, True or False, is compared with <= to 20. But you cannot ask if True/False is less than or equal 20, in C#.
Problem : you can not check two expressions without Combining them.
Solution : i think you want to check whether value is in beteween 1 and 20
You can Use Logical AND && operator for checking this
Try This:
if (value >= 1 && value <= 20)
{
}
1 <= value evaluates out to be bool (false if value is less than 1 and true otherwise).
So it evaluates out to be (true <= 20) or (false <=20) and error states clearly that you cannot use operator <= to compare bool and double.
You need and (&&) operator to do comparison:
if (1 <= value && value <= 20)
{
}