Is it possible to get the property that an attribute refers to using Roslyn syntax analysis? I was able to get the attribute name as follows:
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Linq;
namespace Project1
{
internal class Program
{
static void Main(string[] args)
{
string sourceCode = File.ReadAllText("TestAttributes.cs");
SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode);
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
AttributeListSyntax node = root.DescendantNodes().OfType<AttributeListSyntax>().First();
IdentifierNameSyntax identifierName = node.Attributes[0].Name as IdentifierNameSyntax;
Console.WriteLine(identifierName.Identifier.Text);
}
}
}
With TestAttributes.cs containing the following:
using System.ComponentModel.DataAnnotations;
namespace Project1
{
public class Person
{
[Range(18, 120, ErrorMessage = "Age must be between 18 and 120")]
public int Age { get; set; }
}
}
However, in this case I'd like to do either of the following:
- Get the node representing the attribute
rangefrom the node representing the propertyAge - Get the node representing the property
Agefrom the node representing the attributerange
Is there any way to do this with the Roslyn syntax analysis API? I'd like to avoid semantic analysis if possible.
Edit
Here's what I tried after @Selvin's comment:
namespace Project1
{
internal class Program
{
static void Main(string[] args)
{
string sourceCode = File.ReadAllText("C:\\Users\\Amine.Aboufirass\\Desktop\\TEMP\\user-story-425155\\syntax-analysis\\Project1\\TestAttributes.cs");
SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode);
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
AttributeListSyntax node = root.DescendantNodes().OfType<AttributeListSyntax>().First();
IdentifierNameSyntax identifierName = node.Attributes[0].Name as IdentifierNameSyntax;
IdentifierNameSyntax correspondingIdentifierName = node.Parent as IdentifierNameSyntax;
Console.WriteLine(identifierName.Identifier.Text);
Console.WriteLine(correspondingIdentifierName.Identifier.Text);
}
}
}
Unfortunately I'm now getting a runtime error.
nodewhich is attribute...node.Parentis propertyAge... if you would haveAge'sPropertyDeclarationSyntaxsome element of node of typeAttributeListSyntaxwould be again attribute ... what is the definitive goal?PropertyDeclarationSyntaxnotIdentifierNameSyntaxuse((PropertyDeclarationSyntax)node.Parent).Identifier