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. How to use Guard Clauses in C#

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 How to use Guard Clauses in C# We can check list of all available methods after typing Guard and dot.

We can call above validator like this : How to use Guard Clauses in C#

Using Ardalis.GuardClauses

Let’s see how can we make our custom clause via this library : How to use Guard Clauses in C#

On same pattern as we did previously we can call this like this How to use Guard Clauses in C#

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.

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place