November 28, 2023

C# Caller Argument Expression Attribute

The System.Runtime.CompilerServices.CallerArgumentExpressionAttribute enables you to receive the expression passed as an argument. It captures the expression passed for another parameter as a string.

This would be helpful specially in diagnostic libraries which need to provide more details about the expressions passed to arguments. By providing the expression that triggered the diagnostic, in addition to the parameter name, developers have more details about the condition that triggered the diagnostic.

Lets say we have this method to log the method name.

public static void LogMethodName(string name, 
                 [CallerArgumentExpression("name")] string? message = null)
{
   if (string.IsNullOrEmpty(name))
   {
      //we are printing the 'message' which represents the actual expression 
      //being passed for parameter 'name'
      throw new ArgumentException($"Argument validation: <{message}>", name);
   }

   Console.WriteLine($"Method {name} is called.");
}

Here we are calling above method:

public static void RegisterUser()
{
    LogMethodName(nameof(RegisterUser));
}

In RegisterUser method, we are calling LogMethodName with the value as name of RegisterUser. The expression used for name parameter, is injected by the compiler into the message argument.

In this example, the expression passed for the name parameter is nameof(RegisterUser), so the value of message parameter in LogMethodName is "nameof(RegisterUser)"

References:

1 comment:

  1. This article on the Caller Argument Expression attribute is enlightening! Just like DV Hosting boosts your hosting capabilities, understanding this feature can improve your coding practices.

    ReplyDelete