How to use Guard Clauses in C#
What are guard clauses
Guards adhere to an early return policy, promptly signaling issues through exceptions when conditions are not met. The obligation lies with the developer to appropriately handle these exceptions, mitigating the risk of unintended behaviors.
For example: a specific condition could be that value should not be null or empty e.g. connection string, encryption or decryption keys etc.
How to implement guards clauses in .NET
We have two ways to do that :
-
Custom clauses
-
Using nuget package
How to write custom guard clause
Make a static method in a static class for your desired purpose.
And then call it wherever needed.
public static class Guard
{
public static void IsNullOrEmpty(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException($"{parameterName} cannot be null or empty");
}
}
}
In this way our code gives more readability and instead of checking null condition and throwing exception everywhere we can do it from one place.
Using .NET libraries for guards
There are bunch of libraries that can be helpful in this cause :
-
Guard.Net
-
Ardalis.GuardClauses
Second one is more famous but I use both because of different available methods.
Using Guard.Net
This example demonstrates how can we make a Guard for validating Regex using Guard.Net
using GuardNet;
public static class GuardValidation
{
public static void RegexValidator<T>(T value, string regex, string propertyName)
{
Guard.NotIsMatch(
Convert.ToString(value),
propertyName,
regex,
propertyName + " is not valid Field");
}
}
We can check list of all available methods after typing Guard and dot.
We can call above validator like this :
public static class RegexPatterns
{
public static string TokenPattern => @"^([a-zA-Z0-9]*)$";
}
public static class GuardValidation
{
public static void RegexValidator<T>(T value, string regex, string propertyName)
{
Guard.NotIsMatch(
Convert.ToString(value),
propertyName,
regex,
propertyName + " is not valid Field");
}
}
// Usage
GuardValidation.RegexValidator(inputToken, RegexPatterns.TokenPattern, "Public Token");
Using Ardalis.GuardClauses
Let’s see how can we make our custom clause via this library :
public static class RegexPatterns
{
public static string TokenPattern => @"^([a-zA-Z0-9]*)$";
}
public static class GuardValidation
{
public static void RegexValidator<T>(T value, string regex, string propertyName)
{
Guard.NotIsMatch(
Convert.ToString(value),
propertyName,
regex,
$"{propertyName} is not a valid field.");
}
}
// Usage
GuardValidation.RegexValidator(inputToken, RegexPatterns.TokenPattern, "Public Token");
On same pattern as we did previously we can call this like this
public static class GuardValidation
{
public static void IsNullOrEmpty(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException($"{parameterName} cannot be null or empty");
}
}
}
// Usage
string name = null; // It could be any property
GuardValidation.IsNullOrEmpty(name, nameof(name));
How are they different from validation
Guards and validation serve different roles in development.
Guards quickly stop the program and throw an exception if something unexpected happens. It’s like a safety net that developers need to handle when things go wrong.
Validation, on the other hand, carefully checks all the data in a model, making detailed error messages for anything that doesn’t fit. It’s great for making sure the data follows the rules of the business.
In short, guards stop problems early, while validation is good for making sure everything fits the plan.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place