Wednesday, November 2, 2022

.NET 7.0: ArgumentNullException.ThrowIfNullOrEmpty()

In this post, let's have a look at this nice little feature that's available with .NET 7 and C# 11.0.

With .NET 6 and C# 10.0, we have got a simplified method to check an Argument for null (I have written a post a few months ago: C# 10.0: Nice Little Features).

ArgumentNullException.ThrowIfNull(argument);

But if the argument type is a string, and you need to check it for Empty, we had to fall back to the old approach, which is something like below.

string @string = "";

if (string.IsNullOrEmpty(@string))
{
    throw new ArgumentNullException(nameof(@string));
};

And with .NET 7 and C# 11.0, we don't have to do that anymore. We now have: ArgumentException.ThrowIfNullOrEmpty()

string @string = "";

ArgumentNullException.ThrowIfNullOrEmpty(@string);

I really like this, It's a small thing, but of course, small things matter.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment