Just Found Out About CallerArgumentExpression in C#

A few weeks ago, I was reading some shared code in my team. There was a method that looked simple, but something new caught my eye. It used an attribute I never saw before: CallerArgumentExpression. I didn’t know what it was, so I started to learn more about it. Now I want to share what I found.

CallerArgumentExpression is a feature in C# that helps you get the expression passed to a method parameter, as a string. It was added in C# 10. This is useful when you want to write better error messages or logs, without asking the caller to write the parameter name manually.

Before this, if you wanted to throw an exception and include the name of the argument, you had to write it like this:

if (value == null)
{
  throw new ArgumentNullException(nameof(value));
}

But now, with CallerArgumentExpression, you can write a helper method that does this for you, and it will automatically get the expression from the caller.

Example Here is a simple example I made using a generic type:

public static class Check
{
  public static T NotNull<T>(T argument, [CallerArgumentExpression("argument")] string paramName = "")
  {
    if (argument == null)
    {
      throw new ArgumentNullException(paramName, "Value cannot be null");
    }

    return argument;
  }
}

And you can use it like this:

string data = null;
Check.NotNull(data);

If data is null, the exception will say that the problem is with data, not just some generic message. This makes debugging easier.

This feature is small, but very helpful. It makes shared utility methods cleaner and safer. You don’t need to repeat yourself or worry about forgetting nameof(...). It also helps when writing guard clauses or validation libraries.

I think I will start using this more in my own code. Maybe you will too :)

Reference https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/caller-argument-expression