Skip to content

Caller argument expressions C# 10.0code reduction

Allow methods to capture the code passed in an argument at compile time.

Caller info attributes C# 5.0 have been useful for things like capturing variable names.

C# 10.0 provides a CallerArgumentExpression attribute can be applied to on a method parameter in order to capture the code passed to another parameter.

Code

C#
ArgumentNullException.ThrowIfNull(customerId);

customers.Find(c => c.Id == customerId);
// ...
Customer Find(Func<Customer, bool> predicate, [CallerArgumentExpression("predicate")] string code = "")
{
    return db.Customers.FirstOrDefault(predicate)
        ?? throw new EntityNotFoundException("Could not find Customer matching " + code);
}
C#
if (customerId == null) throw new ArgumentNullException("customerId");

customers.Find(c => c.Id == customerId, "c => c.Id == " + customerId);
// ...
Customer Find(Func<Customer, bool> predicate, string code = "")
{
    return db.Customers.FirstOrDefault(predicate)
        ?? throw new EntityNotFoundException("Could not find Customer matching " + code);
}

Notes

  • This enabled the ArgumentNullException.ThrowIfNull helper method to be added to the .NET Framework.
  • This feature makes nameof C# 6.0 somewhat redundant.

More information