---
title: "Writing new guards with extensions in C# 14"
description: "In C# we have many nice guards sitting on top of static exceptions classes like `ArgumentNullException`, `ArgumentOutOfRangeException`, etc: As `ArgumentException.ThrowIfNullOrEmpty`, `ArgumentException.ThrowIfNullOrWhiteSpace`. Now we can extend them easily!"
updated: 2025-05-19
tags: ["C#", "C# 14", ".NET", ".NET 10"]
canonical: "https://steven-giesel.com/blogPost/e2552b7a-293a-4f46-892f-95a0cd677e4d/writing-new-guards-with-extensions-in-c-14"
---

# Writing new guards with extensions in C# 14

In C# we have many nice guards sitting on top of static exceptions classes like `ArgumentNullException`, `ArgumentOutOfRangeException`, etc: As `ArgumentException.ThrowIfNullOrEmpty`, `ArgumentException.ThrowIfNullOrWhiteSpace`. Now we can extend them easily!

## Extensions to the rescue
The new feature of C# 14 is that we can also extend type definitions with functions. This means we can add new guards to existing classes. If we want to have this "very useful": *"Throw if our string has exactly one character"* semantics, we can do something like this:

```csharp
static class EnumExtensions
{
    extension(ArgumentException)
    {
        public static void ThrowIfHasOneCharacter(string argument, [CallerArgumentExpression("argument")] string? paramName = null)
        {
            if (argument.Length == 1)
            {
                throw new ArgumentException($"Argument '{paramName}' has exactly one character but shouldn't have.", paramName);
            }
        }
    }
}
```

Which then can be used like this:

```csharp
public class MyClass
{
    public void MyMethod(string argument)
    {
        ArgumentException.ThrowIfHasOneCharacter(argument);
    }
}
```

That fits especially well with other already existing guards:

```csharp
public class MyClass
{
    public void MyMethod(string argument)
    {
        ArgumentException.ThrowIfNullOrEmpty(argument);
        ArgumentException.ThrowIfHasOneCharacter(argument);
    }
}
```

Of course this is an overly simplified example. But you get the idea. We get something which makes it look and feel like the existing guards.