Menu
Coddy logo textTech

Short-Circuit Evaluation

Part of the Logic & Flow section of Coddy's C# journey — lesson 36 of 66.

Short-circuit evaluation is an optimization technique in C# where the second operand of logical AND (&&) and OR (||) operators is evaluated only when necessary.

For logical AND (&&), if the first operand is false, the result will always be false regardless of the second operand:

bool result = false && SomeMethod();

In this example, SomeMethod() will not be called because the first operand is already false.

For logical OR (||), if the first operand is true, the result will always be true regardless of the second operand:

bool result = true || SomeMethod();

Here, SomeMethod() will not be called because the first operand is already true.

This behavior can be used to prevent errors, like checking if an object is null before accessing its properties:

// Safe - if student is null, the right side won't evaluate
if (student != null && student.Grade > 70)
{
    Console.WriteLine("Student passed!");
}
challenge icon

Challenge

Easy

Create a method named ProcessUserInput that takes two arguments:

  • A string (input)
  • An integer (minLength)

The method should:

  1. Check if the input is not null
  2. Check if the input length is at least minLength
  3. Only if both conditions are true, print "Valid input: " followed by the input
  4. If either condition fails, print "Invalid input"

Use short-circuit evaluation to prevent any potential NullReferenceException.

Cheat sheet

Short-circuit evaluation is an optimization technique where the second operand of logical operators is evaluated only when necessary.

For logical AND (&&), if the first operand is false, the second operand is not evaluated:

bool result = false && SomeMethod(); // SomeMethod() won't be called

For logical OR (||), if the first operand is true, the second operand is not evaluated:

bool result = true || SomeMethod(); // SomeMethod() won't be called

This prevents errors by checking conditions in order:

// Safe - if student is null, student.Grade won't be accessed
if (student != null && student.Grade > 70)
{
    Console.WriteLine("Student passed!");
}

Try it yourself

using System;

class ProcessUserInput
{
    public static void processUserInput(string input, int minLength)
    {
        // Write your code here
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow