Search code examples
c#code-generationroslyncode-analysisvsix

Roslyn - how to get property names and types in a class using Roslyn?


I created a VSIX project to read properties of a class, trying to get their names and varriable types as doing sth like below using Roslyn;

string filePath = Path.GetDirectoryName(dte.Solution.FullName) + @"\ProjectName\Models\Products.cs";
        string fileBody = File.ReadAllText(filePath);

        var tree = CSharpSyntaxTree.ParseText(fileBody);
        var root = tree.GetRoot();
        var nodes = root.DescendantNodes();
       
        foreach (var node in Properties)
        {
            // How to get;
            // Get name of the property
            // Get type of property int, string, double etc...
        }

Could you please provide correct way of doing that?


Solution

  • No help, but I found the answer, I put here if someone needs it,

                    foreach (var node in nodes)
                {
                    var properties = node.DescendantNodes().OfType<PropertyDeclarationSyntax>();
    
                    foreach (var property in properties)
                    {
                        Field field = new Field();
    
                        field.Type = property.Type.ToString();
                        field.Name = property.Identifier.ValueText;
                        field.Modifier = property.Modifiers.ToString();
    
                        if (property.AttributeLists.Count > 0)
                        {
                            foreach (var item in property.AttributeLists)
                            {
                                Attribute attribute = new Attribute();
    
                                attribute.FullString = item.Attributes.ToFullString().ToLower();
    
                                if (item.Attributes.First().ArgumentList != null)
                                    attribute.Value = item.Attributes.First().ArgumentList.Arguments.First().ToFullString();
                                
                                field.Attributes.Add(attribute);
                            }
                        }
                        model.Fields.Add(field);
                    }
                }
    

    And my model to capture it;

         public class Field
        {
            public string Name { get; set; }
            public string Type { get; set; }
            public string Modifier { get; set; }
            public List<Attribute> Attributes { get; set; } = new List<Attribute>();
        }
    
    
        public class Attribute
        {
            public string Key { get; set; }
            public string Value { get; set; }
            public string FullString { get; set; }
        }
    
    
        public class Model
        {
            public string Name { get; set; }
            public List<Field> Fields { get; set; } = new List<Field>();
            public ModelTypes ModelType { get; set; }
        }