c# understanding the bool expression - c#

This is a really simple question I am sure, but I cannot figure out why this assertion fails...
basically if IsApple is false or IsBannana is false assertion should fail, however if one of the two is true assertion should pass, could anyone explain why this assertain fails?
[Test]
public void IsApplesOrBannans()
{
bool IsApple = true;
bool IsBannana = false;
if (!IsApple || !IsBannana)
Assert.Fail();
Assert.Pass();
}

What you're saying makes no sense.
Here's how I (and the compiler) understand what you're saying:
basically if IsApple is false or IsBannana is false assertion should fail
If IsApple is false the assertion should fail
If IsBanana is false, the assertion should fail
In other words, if one of them is false, you don't care whether or not the other is also false.
however if one of the two is true assertion should pass
If one of them is true, you don't care whether the other one is also true.
Those requirements contradict each others.
Perhaps you meant "if IsApple is false AND IsBanana is false"; that is, if they are both false.
But what you wrote was "if IsApple is false OR IsBanana is false", that is, if one of them are false.

!IsBannana is true so the if evaluates to true.
I bet you wanted:
if(!IsApple && !IsBananna)
Assert.Fail();

The assert will fail if EITHER is false, it will only pass if BOTH are true.
Edit: I would re-write this as:
if (IsApple || IsBanana)
{
Assert.Pass();
}
else
{
Assert.Fail();
}
Interestingly, the question as posed cannot be answered (since if one is true and the other is false according to the question the expected result is amiguous).

Do this instead:
if(!IsApple && !IsBannana)

if (IsApple != IsBannana)
Assert.Fail();
I think this trick != is a C# FAQ as poor man's XOR

You dont want the case where neither a nor b is false, or rather at least one should be true, so
[Test]
public void IsApplesOrBannans()
{
bool IsApple = true;
bool IsBannana = false;
if (!(IsApple || IsBannana))
Assert.Fail();
Assert.Pass();
}

Your pass condition is IsApple || IsBannana, so your fail condition can be written as:
if (!(IsApple || IsBannana))
Or alternatively you can say both must be false to fail:
if ((IsApple==false) && (IsBannana==false))
Which usually is written as:
if (!IsApple && !IsBannana))
Personally I think the first of these three alternatives is the best. But that's just a stylistic choice. functionally they are equivalent.
Or even better, you could switch your then and else part of the if:
public void IsApplesOrBannans()
{
bool IsApple = true;
bool IsBannana = false;
if (IsApple || IsBannana)
Assert.Pass();
else
Assert.Fail();
}
Or even throw out the if statement entirely:
public void IsApplesOrBannans()
{
bool IsApple = true;
bool IsBannana = false;
Assert.IsTrue(IsApple || IsBannana);
}

Your pass condition contradicts your fail condition, because if only one is true, the other one is false and thus fulfills the fail condition.
if you want it to make sense, change it to this:
if (!IsApple && !IsBanana)
Assert.Fail():
or, if you also don't want it to be an apple and banana at the same time
if (IsApple == IsBanana)
Assert.Fail():

(!A|| !A) = !!(!A || !B) = !(A && B) = !(true && false) --> false

Related

Does the method inside the IF condition always get executed? C#

if (condition)
{
// block of code to be executed if the condition is True
}
So if I have a method which returns boolean and the method is used as the condition for IF, does that method get executed no matter what?
Below is the code I'm working on:
public virtual void WorkTheNextShift(float HoneyConsumed)
{
if (HoneyVault.ConsumeHoney(HoneyConsumed))
{
DoJob();
}
else Console.WriteLine("Not enough honey left!");
}
This is the ConsumeHoney method in the static HoneyVault class:
public static bool ConsumeHoney(float amount)
{
if (amount < honey)
{
honey -= amount;
return true;
}
else return false;
}
Thank you for your help! :)
Additional question:
Is there any official documentation where it says that the condition inside IF will always be executed? I can't seem to find it under Microsoft's .NET documentation, or anywhere else.
In your case, yes: the method will always get executed.
Things can get a little more complex if you have multiple conditions. In this case something called short-circuit evaluation may come into play and the method may not be executed at all if the boolean condition can be satisfied regardless of it's result.
The following examples will help clarify it:
bool A = true;
bool B = false;
bool Test() {
Console.WriteLine("Test was called!");
return false;
}
if (Test()) {
// will call Test
}
if (B || Test()) {
// will call Test since B is false the compiler has to check Test()
}
if (A || Test()) {
// Test won't be called because A is true and the result
// of Test() is not needed. The condition is always true.
}
if (B && Test()) {
// Test won't be called because B is false and the result
// of Test() is not needed. The condition is always false.
}
if (A && Test()) {
// Will call Test since A is true. The compiler needs to check the
// result of Test to properly check the AND condition.
}
In the official documentation the && operator is described as: The conditional logical AND operator &&, also known as the "short-circuiting" logical AND operator.
While the || operator is described as: The conditional logical OR operator ||, also known as the "short-circuiting" logical OR operator
Here is a link to the docs: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators

c# Is there a cleaner way setting the same flag boolean variable to true within multiple if statements

I have an example like this and I was wondering if there was a cleaner way to assign true to the same variable. The if statements are only for example purposes. The question is not about the if statements but just trying to find a cleaner way to do this rather than submitting the same flag to true over and over.
public static bool CheckForCondition(DateTime a, DateTime b, bool conditionFlag)
{
if (a > b)
{
conditionFlag = true;
}
else if (b < a)
{
conditionFlag = true;
}
else if (a == b)
{
conditionFlag = true;
}
return conditionFlag;
}
My goal was to avoid the repetition of the same code and make it cleaner if possible.
This will be fine:
public static bool CheckForCondition(DateTime a, DateTime b, bool conditionFlag)
=> conditionFlag || a >= b;
You accept a bool and overwrite it to true if a is >= b. Because you never set it to false it means it's effectively an OR operation.. The only way you get a false out is if it's a false in and b > a.
The first 2 if statements are basically the same thing you do not need to check both, you could also use greater than or equal to condition to combine the first and third if statements.
conditionFlag = false
if (a >= b)
{
conditionFlag = true;
}
return conditionFlag;
Edit: This assumes that you want the function to return false if none of the conditions are true, otherwise Caius Jard's answer is better. Can also be simplified even more as mentioned by Matthew Watson in the comments.

Will only the last or-operator work with the and-operator?

(Sorry, this is very hard to explain for me)
So even if the ped is aiming, it also checks if the ped exists? or only when the ped's weapon is ready to shoot? (since it's right next to the and operator.)
code
See this little fiddle:
public static void Main()
{
bool result1 = true || false && false;
bool result2 = (true || false) && false;
Console.WriteLine(result1); // Outputs: true
Console.WriteLine(result2); // Outputs: false
}
So braces do matter here. In the first case true is returned even though the final condition is false. That final condition is not evaluated.
In the second case the final condition is evaluated and is crucial for the result.
See more info on c# operators and precedence here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#conditional-logical-and-operator-

Is there a better way to check for boolean logic

I have an xml filelike so
<Config>
<Allowed></Allowed>
</Config>
The Allowed tag is read like this:
string isAllowed = (string)xml.Root
.Element("Config")
.Elements("Allowed")
.SingleOrDefault();
isAllowed is supposed to take a default value of true when
The tag is not present
Is present but is empty
Has any other value other than true, false, yes, or no.
Here is the code which does this:
if (isAllowed == null)
{
DoSomething();
return true;
}
if (isAllowed.Length == 0)
{
DoSomething();
return true;
}
if (isAllowed.Length != 0)
{
if (isAllowed.ToUpper() != "FALSE" && isAllowed.ToUpper() != "NO")
{
DoSomething();
return true;
}
}
There's got to be a better way to do this?
if (isAllowed == null)
{
DoSomething();
return true;
}
if (isAllowed.Length == 0)
{
DoSomething();
return true;
}
Can be replaced with:
if (string.IsNullOrEmpty(isAllowed)
{
DoSomething();
Return true;
}
But actually, given your criteria I think string.IsNullOrWhiteSpace(isAllowed) would be more appropriate as it will return true if the tag's contents are "empty".
Also, you don't need the following condition a second time, because if if the condition was met the first time around the function will return (short circuit evaluation). This means that the statements you currently have in the second If block would never be executed anyway.
if (isAllowed.Length != 0)
My first instinct to make this cleaner was to take the same approach as Jon did in his answer, there's no advantage in repeating it. However, I did consider this as another good design as should you introduce more conditions it will be much cleaner:
private static bool Validate(string isAllowed)
{
var defaultTrueConditions = new[] {"true", "false", "yes", "no"};
if (string.IsNullOrWhiteSpace(isAllowed) ||
defaultTrueConditions.Contains(isAllowed, StringComparer.OrdinalIgnoreCase))
{
DoSomething();
return true;
}
return false;
}
It sounds like you might be better off like this:
// This deals with the nullity aspect. (The "Yes" is just for clarity - it could
// be any value other than "No" or "False" in some form.)
isAllowed = isAllowed ?? "Yes";
bool isFalse = isAllowed.Equals("No", StringComparison.OrdinalIgnoreCase) ||
isAllowed.Equals("False", StringComparison.OrdinalIgnoreCase);
return !isFalse;
Basically the fact that you're defaulting to true means that the return value should only be false if you find an element and it's got a value of No or False, in a case-insensitive way. Note that I've used an ordinal match here - you may want to change that, e.g. to CurrentCultureIgnoreCase or InvariantCultureIgnoreCase.
It's not clear where the DoSomething method call comes in, but I would separate that out anyway. Write one method which just determines the appropriate value, as shown above - and then have:
bool allowed = CheckAllowed(doc);
if (allowed)
{
DoSomething();
}
// And use allowed here too
That's a much cleaner separation to my mind.

What does this snippet of C# code do?

What does result.IsVisible equal?
if(a==b)
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
That depends on the values of obj1.status.abc_Report and obj1.AnotherValue.ToBoolean() (and it all depends on whether a==b or not).
I'm not quite sure of what the real question is here - which bit is confusing you?
One bit which may be confusing you is the shortcircuiting && operator (and possibly the lack of bracing!)
The && operator will only evaluate its right hand side if the left hand side evaluates to true: and the overall result of the expression is true if and only if both sides evaluates to true. (I'm assuming no strange user-defined conversions here.)
So another way of writing it would be:
if (a == b)
{
bool visibility = false;
if (obj1.status.abc_REPORT == 'Y')
{
if (obj1.AnotherValue.ToBoolean() == false)
{
visibility = true;
}
}
result.IsVisible = visibility;
}
Note that a condition comparing Booleans, like this:
obj1.AnotherValue.ToBoolean() == false
would usually be written like this:
!obj1.AnotherValue.ToBoolean()
(Note the exclamation mark at the start - the logical "not" operator.)
The same as this, in many less lines:
if (a==b) {
if (obj1.status.abc_REPORT == 'Y') {
if (obj1.AnotherValue.ToBoolean() == false) {
result.IsVisible = true;
}
else {
result.IsVisible = false;
}
}
else {
result.IsVisible = false;
}
}
In simple words:
If a is equal to b:
result will be visible only if:
object1's status's abc_report is Yes(Y = Yes most probably) AND object1's other value cannot be converted to a Boolean
I'm guess result.IsVisible is a boolean
It will be true if the following conditions are true:
obj1.status.abc_REPORT == 'Y'
and
obj1.AnotherValue.ToBoolean() == false
Also, a == b must be true to enter the initial if
lets go line by line:
if(a==b)
obvious if value of a equals value of b the execute following line
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
result is some object (maybe winforms controls etc) which has a property IsVisible set it to true if obj1.status.abc_REPORT is equal to 'Y' and also obj1.AnotherValue.ToBoolean() is equal to false;

Categories

Resources