Does the method inside the IF condition always get executed? C# - 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

Related

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-

How to terminate a method execution Midway in C#?

I need to exit from a method when a certain condition is reached. The other lines of code should not be executes after exit Condition is reached. what is the best way for this I have tried to use Environment.Exit(0), but it causes problem in my logic.
Exit(0) does not seem to work unless in a loop
We have two possibilities: normal (return) and abnormal (throw) termination:
public static int Factorial(int value) {
// We can't compute factorial for negative and too large values
if (value < 0 || value > 12)
throw new ArgumentOutOfRangeException(nameof(value)); // Abnormal termination
if (value == 0)
return 1; // Normal termination: special case in which we know the answer
...
}
The "return" statement exits condition-blocks aswell as loops and methods.
public void myMethod(int a){
if( 1 == a) {
return;
}
// do something with a
}
As some people have already said before me, return is the way to go.
Here is an example where an if statement compares two integers and returns if they are equal:
public void isEqual(int a, int b) {
if (a == b) {
Console.WriteLine("Integers are equal");
return; //Return to executing the rest of the program.
}
else {
Console.WriteLine("Integers are not equal");
}
}

C# - Foreach loop with if statement

How can I go about doing this so if the "if" statement is true, to skip the code below the foreach loop and to go on with the rest of the program
void()
{
foreach()
{
if()
{
}
}
//code I want to skip if "if" statement is true
}
There's no way to directly do what you want (without "goto" labels -- perish the thought!), but you can use the "break" keyword, and set a variable you can refer to later.
void()
{
var testWasTrue = false;
foreach()
{
if()
{
testWasTrue = true;
break; // break out of the "foreach"
}
}
if( !testWasTrue ) {
//code I want to skip if "if" statement is true
}
}
I know this was already answered, but I figured I'd throw in my 2 cents since nobody considered abstracting the check to a separate method:
void()
{
if (ShouldDoStuff(myCollection))
DoStuff(myCollection);
else
DoOtherStuff(myCollection);
}
private bool ShouldDoStuff(collection)
{
foreach()
{
if ()
return true;
}
return false;
}
This provides a much cleaner code at the higher level for dealing with your algorithms and removes all the clutter discussed about. It cleanly separates the tasks in void() of checking and performing the actions and readers instantly know exactly what the program flow is without having to discern what they're doing with a boolean or break logic lurking about. No single method has more than 1 responsibility or task.
Yeah, it's possible the poster wants to do other work in their foreach, but that's an entirely different discussion and not what was described in their question. If you simply want to check if the given collection (or object) satisfies a certain condition, that check can be moved to a separate method. Even leaves the door open for automated unit tests for all three components.
Even if DoStuff and DoOtherStuff are not abstracted to their own methods, it provides nicer readability and logical flow.
void()
{
bool process = true;
foreach()
{
if()
{
process = false;
break;
}
}
if (process)
{
//code I want to skip if "if" statement is true
}
}
As was mentioned in my comment you may do this through extra bool variable.
void()
{
bool positiveResult; // by default it gets false value
foreach()
{
if()
{
positiveResult = true;
// you may use "break" to skip the loop
break;
}
}
if( !positiveResult )
{
//code I want to skip if "if" statement is true
}
}
The 'break' keyword will break out of the loop.
foreach (someClass a in someArray)
{
if(a.someProperty) // bool property
{
//Stuff to do if that condition is true
doSomethingElse();
//Calling the break keyword will stop the loop and jump immediately outside of it
break;
}
//Other code to run for each iteration of the loop
}
//Here is where execution will pick up either after break is called or after the loop finishes
Only way I know how is a bool flag.
void()
{
bool x = false;
foreach()
{
if()
{
x = true;
break;
}
}
if(!x)
{
//Code to skip if "if" statement is true.
}
}
Not super elegant, but easy.
Edit: beat by 12 secs :)
void()
{
bool skip = false;
foreach()
{
if()
{
skip = true;
}
}
if(!skip)
{
//code I want to skip if "if" statement is true
}
}
If the collection you are iterating through contains The IEnumerable Interface, You could use Any() with a Lambda!
int[] myArray = { 1, 2, 3 };
if( myArray.Any((a) => a == 1) )
{
return;
}
It is read: if my array contains any value a where a is equal to 1, then return out of this function.
Plus if you want to make it harder to read, you can omit the curly braces/brackets.
if( myArray.Any((a) => a == 1) )
return;

How can this recursive function return true?

This is my recursive function :
public bool controllaSelezioneSottopagina(KPage k_oPaginaAttuale, KPage k_oPaginaSuperiore)
{
foreach (KPage k_oSottoPagina in k_oPaginaSuperiore.SottoPagine)
{
if (k_oSottoPagina.ID == k_oPaginaAttuale.ID)
{
return true;
}
else
{
if (k_oSottoPagina.SottoPagine.Count != 0)
{
controllaSelezioneSottopagina(k_oPaginaAttuale, k_oSottoPagina);
}
}
}
return false;
}
I aspect, from where I call it, to get ALWAYS false (the return false at the end of the function, will be the last result that will be returned, EVER).
In fact, sometimes it returns true.
How it is possible? Tried debugging... but I can't find out the mistake...
You call the function once, then it loops, and either returns true or calls itself recussively. It will only return false if it loops through all elements and the condition (k_oSottoPagina.ID == k_oPaginaAttuale.ID) is never met.
Now assume that this condition is actually met in the first level (there was no recursion made yet or all recursive call return).
You call the function once, it loops and for example on the first test this condition is true. Then you will see a return value 'true'
I think this could happen only in first iteration. I mean that only first comparison may result in returning true. Recursive call would never happen then.
Are you saying this code block will never be true in the first call to the function (the first time through the loop)?
k_oSottoPagina.ID == k_oPaginaAttuale.ID
Since you don't return the result of the recursive call, your function either blows the stack, returns true through the first loop at some point, or finishes the loop and returns false.
another alternative to not printing incorrect false in the cases where it does go in the loop is
public bool controllaSelezioneSottopagina(KPage k_oPaginaAttuale, KPage k_oPaginaSuperiore)
{
foreach (KPage k_oSottoPagina in k_oPaginaSuperiore.SottoPagine)
{
if (k_oSottoPagina.ID == k_oPaginaAttuale.ID)
{
return true;
}
else
{
if (k_oSottoPagina.SottoPagine.Count != 0)
{
if(controllaSelezioneSottopagina(k_oPaginaAttuale, k_oSottoPagina))
{
return true;
}
}
}
}
return false;
}

c# understanding the bool expression

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

Categories

Resources