AlwaysLearning
AlwaysLearning

Reputation: 43

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.

Upvotes: 1

Views: 1026

Answers (1)

Loudenvier
Loudenvier

Reputation: 8804

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

Upvotes: 2

Related Questions