ArgumentException.ThrowIfNull and ArgumentException.ThrowIfNullOrEmpty had been introduced as guard clause in .NET 6  and .NET 7 releases. They will help to throw null exceptions cleaner way.

What is ArgumentException

ArgumentNullException is a class in the .NET Framework that represents an exception when a null reference is passed to a method that does not accept it as a valid argument. This exception is thrown when a method or constructor is called with a null argument, and the method or constructor is not designed to handle that.

It is typically thrown by the runtime when a null argument is passed to a method or constructor that doesn't accept it. It can also be thrown explicitly by the developer by using the throw keyword, along with a new instance of the ArgumentNullException class, to indicate that a null argument is not valid for the method or constructor being called.

Prior to C# 10 you may have had code similar to the following using ArgumentNullException.

If the parameter 'Summary' is null, then an ArgumentNullException will be thrown.

Newly added ArgumentNullException guard clause

C# 10 (.NET 6) and C# 11 (.NET 7) introduced an improved way to avoid robust code. They are working like guard clauses.

💥
C# 10 (.NET 6) - ArgumentException.ThrowIfNull

C# 11 (.NET 7) - ArgumentException.ThrowIfNullOrEmpty

Usage

In the preceding code, a new static method called ThrowIfNull and ThrowIfNullOrEmpty have been added to the ArgumentNullException class and allow us to check and throw ArgumentNullExceptions quickly.

Using this kind of guard clauses instead of if statement checks results in cleaner code.


I like it; hopefully, Microsoft can continue adding more guard clauses in future .NET releases.

Until they release, I am using two excellent libraries from the open-source community.

  1. amantinband/throw
GitHub - amantinband/throw: A simple, fluent, extensible, and fully customizable library for throwing exceptions for projects using .NET 6+
A simple, fluent, extensible, and fully customizable library for throwing exceptions for projects using .NET 6+ - GitHub - amantinband/throw: A simple, fluent, extensible, and fully customizable li...

2. ardalis/GuardClauses

GitHub - ardalis/GuardClauses: A simple package with guard clause extensions.
A simple package with guard clause extensions. Contribute to ardalis/GuardClauses development by creating an account on GitHub.

This is a trendy library through .NET people. Which is a set of best practices for input validation and error handling in C# code, developed by Steve Smith (ardalis)

💬
Lets talk guard clauses and above library in the near future. Keep in touch with my blog.
💬
Put your valuable comments on this topic. See ya soon on another blog post. 👊👊
Happy coding....!

Share this post