Search code examples
c#roslynroslyn-code-analysis

Inject method parameter at compiletime using Roslyn


I'm trying to find out wether Roslyn does support the following use-case:

I use a Guard class for parameter validation

public void Foo(string bar)
{
    Guard.NotNull(bar, nameof(bar));
    // ....
}

Nothing fancy and the nameof(...) expression even makes it refactoring-friendly. But it's still redundant. And nothing prevents me from doing something like this

public void Foo(string bar, string baz)
{
    Guard.NotNull(bar, nameof(baz));
    // ...
}

So if there were a way to avoid the nameof(...) part completely that would be nice.

So I would like to enable Roslyn to do something similar to the [CallerMemberNameattribute], just for parameters.

public static class Guard
{
    public static void NotNull(object param, [CallerParameterName]string paramName = "")
    {
        if (param == null)
        {
            throw new ArgumentNullException(paramName);
        }
    }
}

public void Foo(string bar)
{
    Guard.NotNull(bar);
    // ...
}

I don't want to change the code before compiling it (like a refactoring or code fix would). I don't want to see values for arguments annotated with the CallerParameterNameAttribute in source code at all (exactly like I don't see them for CallerMemberName or CallerLineNumber etc.).

I want Roslyn to inject the names of the parameters at compiletime for me.

Both Source Generators and Code Generators can only add source code (not change it) and compile it. The regular Roslyn analyzers also change source code afaik.

Any idea if that part of Roslyn is publicly accessible and where I can find information on how to use it?


Update: I don't want to use an IL Weaver like PostSharp. Just teach Roslyn to treat my custom attribute like one of the System.Runtime.CompilerService attributes.


Solution

  • This is the [CallerArgumentExpression] attribute in C# 10:

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/caller-argument-expression