Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an AttributeSyntax with a parameter

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.

like image 538
devlife Avatar asked Mar 10 '16 21:03

devlife


1 Answers

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.

like image 154
JoshVarty Avatar answered Oct 26 '22 13:10

JoshVarty