I know this post is really old, but since there is now a way in .Net 6 I thought I would share so others know.
You can now use CallerArgumentExpressionAttribute as shown
/// <summary>
/// Will throw argument exception if string IsNullOrEmpty returns true
/// </summary>
/// <param name="str"></param>
/// <param name="str_name"></param>
/// <exception cref="ArgumentException"></exception>
public static void ValidateNotNullorEmpty(this string str,
[CallerArgumentExpression("str")]string str_name=null)
{
if (string.IsNullOrEmpty(str))
{
throw new ArgumentException($"'{str_name}' cannot be null or empty.", str_name);
}
}
Now call with:
param.ValidateNotNullorEmpty();
will throw error: “param cannot be null or empty.”
instead of “str cannot be null or empty”