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
EasyCreate a method named ProcessUserInput that takes two arguments:
- A string (
input) - An integer (
minLength)
The method should:
- Check if the input is not null
- Check if the input length is at least
minLength - Only if both conditions are true, print "Valid input: " followed by the input
- 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 calledFor logical OR (||), if the first operand is true, the second operand is not evaluated:
bool result = true || SomeMethod(); // SomeMethod() won't be calledThis 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
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety