I'm trying to use Roslyn to create a parameter that looks something like this:
[MyAttribute("some_param")]
Now I can easily create the AttributeSyntax
but can't figure out how to add an argument to the ArgumentList
porperty using the .AddArguments(ExpressionSyntax)
method. I'm just not sure what I need to do to create the appropriate expression.
I'm a fan of the SyntaxFactory.Parse*
methods. (They're usually easier to understand)
You could use the following to generate the attribute you're looking for:
var name = SyntaxFactory.ParseName("MyAttribute");
var arguments = SyntaxFactory.ParseAttributeArgumentList("(\"some_param\")");
var attribute = SyntaxFactory.Attribute(name, arguments); //MyAttribute("some_param")
var attributeList = new SeparatedSyntaxList<AttributeSyntax>();
attributeList = attributeList.Add(attribute);
var list = SyntaxFactory.AttributeList(attributeList); //[MyAttribute("some_param")]
Alternatively you could use hand-crafted approach from Kirill's RoslynQuoter tool. But I think the fact that no one wants to write that code without his tool is telling... ;)
The manual approach looks like:
var attributeArgument = SyntaxFactory.AttributeArgument(
SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.StringLiteralToken, "some_param", "some_param", default(SyntaxTriviaList))));
var otherList = new SeparatedSyntaxList<AttributeArgumentSyntax>();
otherList = otherList.Add(attributeArgument);
var argumentList = SyntaxFactory.AttributeArgumentList(otherList);
var attribute2 = SyntaxFactory.Attribute(name, argumentList);
In your example you want to add a StringLiteralExpression
as your argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With