Guard Clauses
Part of the Logic & Flow section of Coddy's C# journey — lesson 19 of 66.
Guard clauses are conditional statements at the beginning of a method that check for edge cases or invalid inputs and return early if those conditions are met.
Let's create a method without a guard clause:
public void ProcessOrder(Order order)
{
if (order != null)
{
// Process the order
// Many lines of code here...
}
}Now, let's rewrite it with a guard clause:
public void ProcessOrder(Order order)
{
if (order == null)
{
return; // Guard clause - exit early if order is null
}
// Process the order
// Many lines of code here...
}Guard clauses improve readability by reducing nesting and handling exceptional cases at the beginning of a method.
Challenge
EasyCreate a method named DivideNumbers that takes two integers, numerator and denominator.
- Add a guard clause to check if the denominator is zero.
- If denominator is zero, print: "Cannot divide by zero" and return 0.
- Otherwise, divide the numerator by the denominator and return the result.
Cheat sheet
Guard clauses are conditional statements at the beginning of a method that check for edge cases or invalid inputs and return early if those conditions are met.
Without guard clause:
public void ProcessOrder(Order order)
{
if (order != null)
{
// Process the order
// Many lines of code here...
}
}With guard clause:
public void ProcessOrder(Order order)
{
if (order == null)
{
return; // Guard clause - exit early if order is null
}
// Process the order
// Many lines of code here...
}Guard clauses improve readability by reducing nesting and handling exceptional cases at the beginning of a method.
Try it yourself
using System;
public class Program
{
public static int DivideNumbers(int numerator, int denominator)
{
// Write your code here
}
public static void Main()
{
// Read inputs from console
int numerator = Convert.ToInt32(Console.ReadLine());
int denominator = Convert.ToInt32(Console.ReadLine());
// Call the DivideNumbers method
int result = DivideNumbers(numerator, denominator);
// Print the result
Console.WriteLine(result);
}
}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