Validation throwing generic ‘Value cannot be null’ messages? CallerArgumentExpression shows which argument failed.
Old Generic Message:
public void ProcessUser(User user)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
// Error: "user cannot be null" - not very helpful in complex code
}
With CallerArgumentExpression:
public void ThrowIfNull(T value, [CallerArgumentExpression("value")] string? paramName = null) { if (value == null) throw new ArgumentNullException(paramName, $"Argument '{paramName}' cannot be null"); } public void ProcessUser(User user) { ThrowIfNull(user); // Error: "Argument 'user' cannot be null" ThrowIfNull(user.Settings?.Profile); // Error: "Argument 'user.Settings?.Profile' cannot be null" // Shows exact expression that was null! }
Debugging becomes way easier!
