I am writing a source generator but am struggling to get the value of an argument passed to the constructor of my attribute.
I inject the following into the compilation:
namespace Richiban.Cmdr
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class CmdrMethod : System.Attribute
{
private readonly string _alias;
public CmdrMethod(string alias)
{
_alias = alias;
}
}
}
And then in my sample application I have the following:
public static class InnerContainerClass
{
[CmdrMethod("test")]
public static void AnotherMethod(Data data)
{
Console.WriteLine($"In {nameof(AnotherMethod)}, {new { data }}");
}
}
This compiles without errors or warnings and I am successfully able to find all methods that have been decorated with my CmdrMethod
attribute, but I am unable to get the value passed to the attribute because, for some reason, the ConstructorArguments
property of the attribute is empty:
private static ImmutableArray<string> GetAttributeArguments(
IMethodSymbol methodSymbol,
string attributeName)
{
var attr = methodSymbol
.GetAttributes()
.Single(a => a.AttributeClass?.Name == attributeName);
var arguments = attr.ConstructorArguments;
if (methodSymbol.Name == "AnotherMethod")
Debugger.Launch();
return arguments.Select(a => a.ToString()).ToImmutableArray();
}
Have I misunderstood this API? What am I doing wrong?