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:

C# documentation comments - para and cref

C# documentation comments use XML elements to define the structure of the output documentation. It helps to write the information about code and makes it more readable and understandable.

<para> tag

The <para> tag can be used inside a tag, such as <summary>, <remarks>, or <returns>. It allows you to add structure to the text.

Here the <para> is used to add another line (paragraph) in the summary section.

/// <summary>
/// This property will keep the type of project.
///     <para>
///         The Type of project defined in the document.
///     </para>
/// </summary>
public string ProjectType { get; set; }

It will display this information on mouse hover like this:

cref attribute

The cref attribute in an XML documentation tag means "code reference." It specifies that the inner text of the tag is a code element, such as a type, method, or property.

Here the cref attribute is referencing another class which contains constant string values.

/// <summary>
///     <para>
///         Use <see cref="MyNamespace.ProjectStatus"/> class.
///     </para>
/// </summary>
public string Status { get; set; }

On mouse hover it will display like this:

Note that the ProjectStatus will appear as link, and will take you to the definition of class when clicked.

References: