Guard Clauses in C#

How to use Guard Clauses in C#?

Today we are going to discuss.

  • What are guard clauses?
  • How to implement them in .NET
  • Multiple ways of implementation
  • How are they different from validation

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 the 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 do you write a custom guard clause?

Make a static method in a static class for your desired purpose.

And then call it wherever needed.

Guard.IsNullOrEmpty(name,nameof(name)); //Call guard like this

public static class Guard
{
	public static void IsNullOrEmpty(string value,string param)
	{
		if(string.IsNullOrEmpty(value))
		{
			throw new ArgumentException($"param cannot be null or empty...");
		}
	}
}

In this way, our code gives more readability, and instead of checking null conditions and throwing exceptions everywhere, we can do it from one place.

Using .NET libraries for guards

There are a bunch of libraries that can be helpful in this cause.

  • Guard.Net
  • Ardalis.GuardClauses

The second one is more famous, but I use both because of the different available methods.

Using Guard.Net

This example demonstrates how we can 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")
	}
}

We can check the list of all available methods after typing Guard and dot.

We can call the above validator like this.

string tokenPattern =  @"\{token:(.*)\}";

GuardValidation.RegexValidator(inputToken,tokenPattern,"Public token")

Using Ardalis.GuardClauses

Let’s see how we can make our custom clause via this library.

using Ardalis.GuardClauses;

public static class GuardValidation
{
	public static void IsNullOrEmpty(string value,string param)
	{
		Guard.Against.NullOrWhiteSpace(value,param);
	}
}

On the same pattern as we did previously, we can call this.

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.


Recommended Free Ebook
Similar Articles