Skip to content

Extended nameof scope C# 11.0readabilitycorrectness

Use nameof with method parameters in attributes on that method.

The nameof operator could not reference method parameters when used in attribute arguments on the method or its parameters. This forced developers to use hardcoded strings that could silently become stale when parameters were renamed.

C# 11 extends the scope of nameof so that method parameter names are accessible in attributes on the method, its parameters, and its type parameters.

Code

C#
[return: NotNullIfNotNull(nameof(input))]
public string? Process(string? input)
{
    return input?.Trim();
}

public void Copy(
    [DisallowNull] string source,
    [CallerArgumentExpression(nameof(source))] string? expr = null)
{
}
C#
[return: NotNullIfNotNull("input")]
public string? Process(string? input)
{
    return input?.Trim();
}

public void Copy(
    [DisallowNull] string source,
    [CallerArgumentExpression("source")] string? expr = null)
{
}

More information