Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a method named DivideNumbers that takes two integers, numerator and denominator.

  1. Add a guard clause to check if the denominator is zero.
  2. If denominator is zero, print: "Cannot divide by zero" and return 0.
  3. 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);
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow