Exceptions and Defensive Coding
Guard Clauses
A guard clause handles invalid input before the main work continues.
Guard Clauses
GuardClauses.cs
using System;
class Program
{
static int ShippingCost(int quantity)
{
if (quantity <= 0)
{
return 0;
}
return 5 + quantity;
}
static void Main()
{
int quantity = ;
int cost = ShippingCost(quantity);
Console.WriteLine($"quantity={quantity}");
Console.WriteLine($"cost={cost}");
}
}
using System;
class Program
{
static int ShippingCost(int quantity)
{
if (quantity <= 0)
{
return 0;
}
return 5 + quantity;
}
static void Main()
{
int quantity = ;
int cost = ShippingCost(quantity);
Console.WriteLine($"quantity={quantity}");
Console.WriteLine($"cost={cost}");
}
}
using System;
class Program
{
static int ShippingCost(int quantity)
{
if (quantity <= 0)
{
return 0;
}
return 5 + quantity;
}
static void Main()
{
int quantity = ;
int cost = ShippingCost(quantity);
Console.WriteLine($"quantity={quantity}");
Console.WriteLine($"cost={cost}");
}
}
guard clause
A guard clause returns early when a value should not continue through a method.