If statement not checking multiple values - c#

I am trying to test and see if 4 user inputted answers are correct(I have tested without using if statements and all variables are correct), however it seems to only be checking 1 out of the 4 conditions in the if statement. I tried using both the single & and double && operator, and neither made a difference?
if(isOneCorrect.ToUpper() == checkBox1.Checked.ToString().ToUpper() &&
isTwoCorrect.ToUpper() == checkBox2.Checked.ToString().ToUpper() &&
isThreeCorrect.ToUpper() == checkBox3.Checked.ToString().ToUpper() &&
isFourCorrect.ToUpper() == checkBox4.Checked.ToString().ToUpper())
{
MessageBox.Show("you won!");
}
What can I do to make the if statement make sure EVERY condition of the 4 is correct?

The boolean operators/expressions in C# shortcut - this means if you have several sequential boolean operators (like you have) then expression evaluation will stop when the overall result can no longer be changed.
So, to explain that a little more: you have four && operators. For the if statement to valuate to true all of those ANDed expressions need to evaluate to true. If the first one fails there is no point evaluating the rest, the final result will not change.
When comparing strings you should use the string.Equals() extension method.
However you did state in the comments that isOneCorrect is boolean; if checkBox1.Checked is also boolean then you do not need to convert anything to string, just compare the two booleans. If checkBox1.Checked is a nullable bool (bool?) then use the HasValue and Value properties to access it as a bool.

Related

If Statement with Multiple Conditions vs Individual If Statements [duplicate]

This question already has answers here:
"If" statement - Order of validation of objects?
(6 answers)
Closed 2 years ago.
I would like to check each condition and return if true.
Is it better to have:
1. Multiple conditions in a single if statement?
if (string.IsNullOrEmpty(myStr) ||
myBool == true ||
myList.Count == 0)
{
return;
}
2. Or multiple if statements, each checking a different condition.
if (string.IsNullOrEmpty(myStr))
{
return;
}
if (myBool == true)
{
return;
}
if (myList.Count == 0)
{
return;
}
If myStr is Empty.
My thought is that the first way checks all 3 conditions before it reaches the return (or does it)?
And the second way only has to check the 1st condition string.IsNullOrEmpty, reaches the return, and doesn't have to process the other 2 condition checks below it.
Or does the compiler optimize the code to work most efficient no matter how the source is written?
They are equivalent. The || operator short-circuits, so as soon as it reaches a condition that is true, it stops checking other conditions and returns true.
The | operator does not short-circuit, so it would evaluate every operand before returning a value.
Same goes for && and & but with false. As soon as a false condition is reached, the && operator returns false.
So your two methods are functionally identical. Use whichever one you think is the cleanest, easiest to infer intent, etc.
Or does the compiler optimize the code to work most efficient no matter how the source is written?
Well, the optimizer can make changes to code for efficiency, but it cannot change the functional behavior, meaning it won't change the order of the operations. Imagine you had something like:
if ((x == 0) || (y/x > 1))
this is a common way to prevent divide-by-zero errors. If the compiler could rearrange the operands, then it could introduce divide-by-zero errors.
It's a matter of preference really, as both will result in the same overall performance. Both are equivalent to each other. By default, C# uses short-circuit evaluation, meaning the if statement will stop as soon as it finds an expression that evaluates to true. Most of the time, I've seen it written as a single if statement, but separate checks can be easier for debugging if you want to put a breakpoint on one of the specific conditions.
Also of note, although if (myBool == true) will work, you don't have to explicitly equate it to true. The if statement just has to evaluate to true, so you can write it as if (myBool). Again it's personal preference, but it's shorter and can make it easier to read.
Lastly, you might consider using string.IsNullOrWhiteSpace, which is just like string.IsNullOrEmpty but also checks if the string only contains spaces, tabs, etc., with no content.

Two inline Condition Check

i am trying to avoid extra lines of code. so i am running this by you guys to see if it correct. i wrote an inline condition to check for 2 elments in an object.
if the Notification Date (EndsAt) is assigned and the errormessage is NullorEmpty or the Notification Date is not assigned and the errormessage is not NullorEmpty then return "09".
if ((Notification.EndsAt.HasValue && String.IsNullOrEmpty(Notification.ErrorMessage)) || (!Notification.EndsAt.HasValue && !String.IsNullOrEmpty(Notification.ErrorMessage)))
{
return "09";
}
thanks for your help.
What exactly is your question?
Are my conditions correct in checking 2 elements?
If you're asking if your conditions are correct and do what you ask them to do, then that looks OK. The parentheses and bangs go where they should.
Is there any way I can reduce the condition checks?
Can't answer that since you didn't mention what you want to return for cases where:
EndsAt is not Assigned & ErrorMessage IS NullorEmpty
EndsAt is assigned & ErrorMessage IS NOT NullorEmpty
Can I improve performance and readability?
Since the conditional logic here depends on whether EndsAt hasValue and if ErrorMessage is null or empty, you could just store them in variables and compare those variables with the boolean logic you supplied. This reduces length of code (and improves readability), and if getting those boolean values multiple times in your program takes awhile, having them as local variables will improve performance. (think about how saving the count of elements in an array and using it multiple times (while it remains unchanged) is more efficient than calling the count method multiple times when you know the count won't change.

AND operation in C#

I want to perform an AND operation. My inputs are 2 objects. It could be a string like "true" or it could be an expression like "1==1" as well. When using && operator, am getting an exception that String was not recognized as a valid boolean.
Please help me.
return Convert.ToBoolean(obj[0]) && Convert.ToBoolean(obj[1]);
Sorry for the earlier post which was not clear enough.
Converting "1==1" to a boolean is not possible for the Convert.ToBoolean method. It just converts the strings true and false.
You will have to either write a expression evaluator yourself, or use some kind of library to parse your string to a boolean (like Flee for example)
First make sure obj[0], obj[1] will only contain 1 or 0(char or integer).
Because Convert.ToBoolean does not understand anything other than 1 or 0.
The below one will work
Convert.ToBoolean(true) && Convert.ToBoolean(1==1)
Why use a string?
The conversion will not evaluate code, it will check if the supplied data is possible to convert to a bool and do so if possible.
Your function will always return true if it was working, cause 1 is always equal to 1, and true is always true.
This is nearly impossible as C# is strongly type language.
What you trying to do is for weakly types languages like JS. "1==1" will work for JS, not for C#.
Remove quotes in order to make it work(You might as well remove first operand, as it doesn't make any sense):
return ( 1 == 1 );

How to stop execution of a while loop's condition, if the condition fails

I've got a while-loop, with a loop condition like so:
while (i != repetitionString.Length || !repetitionString[i].Equals(')'))
The first part of the condition checks to see that the end of the collection is not reached. Is it possible to not execute the part following || after the left side's condition is not met? The reason behind this is that if the left side's condition is not met, then this means that the collection is out of bounds, and hence the right side's evaluation/checking will throw an exception.
Is it possible to do this?
you just simply use && instead of ||. Since the right condition is supposed to be checked only if the first one has returned true.
This is what will happen anyway - the boolean condition on the right is only ever executed if the left one evaluates to false. You can force the right one to execute as well by using binary logic ( single |), but that is exactly not what you want to do, so your current statement will execute just fine.
It looks like what you really want is:
while (i < repetitionString.Length && repetitionString[i]!=")")
{
}
Short circuiting is already occurring.
My guess is that repetitionString is a zero-based index, while the .Length returns the total count. So you'll want to modify the if to stay in bounds:
while (i != (repetitionString.Length - 1) || !repetitionString[i].Equals(')'))
This looks equivalent to:
if (attribute != null || attribute.value != null)
because you can't use
if (attribute.value != null)
as this will raise an error when attribute == null, so I think your code is correct?
When the condition
i != repetitionString.Length
is met, the code will skip the part after the ||
Because it is an OR expression, there's no need to check the 2nd part of the condition when the first part of the condition returns true.
When you use && instead of ||, both conditions will always be checked. This is not what you want to do here.

need explanation, binary operator | working with boolean types?

I'm reading an source code, I found a statement like this:
if (Char.IsWhiteSpace(text[i]) | GetSpecialChars.Contains(text[i]))
Initially,I thought it was typo,instead || (or) operator. But for my surprise, it was compiled. how to it's possible? is | equivalent to || with boolean types?
Thanks in advance.
I'd suggest that it probably is a typo, though it will still work.
The reason boolean | is so rarely seen is that:
Much of the time || is the only one that is correct. If the expression on the right hand side would throw if the expression on the left-hand was true such as in x == null || x.Length == 0 which would successfully return true for a null or zero-length string or array while x == null | x.Length == 0 which would throw an exception for a null string or array as the Length property would still be examined.
Most of the rest of the time || will be faster. It might be nothing but a couple of clock cycles faster (though it could also be more if the expression on the rhs is expensive), but it hardly counts as a premature optimisation that we're all in the habit of using that form. (Just how much effort you put into deciding which goes on the left and which on the right may be another matter).
Some constructs that use it by one-line fans are rather unclear as far as readabilty goes.
The example in the question falls under point two. The only effect of | rather than || here in practice is a few nanoseconds of waste. Not that it matters, but it does lead to || being the habit to fall into.
(If on the other hand a property called GetSpecialChars or a method called Contains has a side-effect that means it has to be called, that property really needs to be renamed to make it clearer!).
About the only time it's useful is either because we really need some side-effect of the right-hand expression to take place, or in the assignment form based on it, |=.
In the former case, it's always worth considering an alternative of evaluating both expressions in separate statements and then ORing the result afterwards, to make it clearer that you care about the side-effect as well as the result.
In the latter case, it can make for more readable code, or at least to code that's more readable to some people! But many find it obscures things.
|| is the short-circuiting version of |. In your if statement, the GetSpecialChars.Contains method will be executed even if the character is white space, whereas || would halt evaluation and not execute the right side.
There is no mistake, this is a boolean OR operator, as opposed to the OR ELSE operator represented by ||. The difference is that the regular OR does not short-circuit, while OR ELSE does.
In your specific case, GetSpecialChars.Contains(text[i]) will be called even if Char.IsWhiteSpace(text[i]) returns true. If you replace | with ||, this would no longer happen (i.e. GetSpecialChars.Contains(text[i]) will not get called if Char.IsWhiteSpace(text[i]) is true).
The | operator in general has two meanings as used with integrals and used with booleans. In the first case it calculates the bit-wise OR of the integrals whereas in the latter case it calculates the logical OR when used with boolean values.
The second case (the logical-OR case) brings another two meanings:
"|" calculates the logical OR with the restriction that it evaluates both values i.e. x | y == false if and only if both x and y are false.
"||" does the same thing but only evaluates the second operand if necessary. So in the former example x || y would evaluate to true as soon as x is evaluated to true without looking at y.
You can refer directly to the MSDN documentation for that here and here
Hope this helps.

Categories

Resources