Reputation: 147
How is it possible (maybe through Reflection or Roslyn APIs) to get the list of internal variables that are used in a class method?
For example, in the following code:
class C1{
private int var1;
public string var2;
void action1()
{
int var3;
var3=var1*var1;
var2="Completed";
}
}
I would like to get var3,var1 and var2 as the list(as name and type) of variables used in the action1() method.
Secondly, I need to identify which of the above variables appear on the left side of an expression; i.e., their values have been modified in this method.
I think the answer lies in using Roslyn, but I have no idea how. Thanks!
Upvotes: 5
Views: 2088
Reputation: 13182
As @xanatos mentioned, it is not possible get this information from compiled assembly. You should use Roslyn for this task and have access to the source code. This answer explains how you can retrieve variables https://stackoverflow.com/a/23543883/2138959 and this article can be a good start Getting Started C# Semantic Analysis.
Going through latter article you could came up with following code:
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Roslyn
{
internal class Program
{
private static void Main()
{
var tree = CSharpSyntaxTree.ParseText(@"
class C1{
private int var1;
public string var2;
void action1()
{
int var3;
var3=var1*var1;
var2=""Completed"";
}
}
");
var root = (CompilationUnitSyntax) tree.GetRoot();
var variableDeclarations = root.DescendantNodes().OfType<VariableDeclarationSyntax>();
Console.WriteLine("Declare variables:");
foreach (var variableDeclaration in variableDeclarations)
Console.WriteLine(variableDeclaration.Variables.First().Identifier.Value);
var variableAssignments = root.DescendantNodes().OfType<AssignmentExpressionSyntax>();
Console.WriteLine("Assign variables:");
foreach (var variableAssignment in variableAssignments)
Console.WriteLine($"Left: {variableAssignment.Left}, Right: {variableAssignment.Right}");
}
}
}
Which produces following output:
Declare variables:
var1
var2
var3
Assign variables:
Left: var3, Right: var1*var1
Left: var2, Right: "Completed"
Make sure to install Microsoft.CodeAnalysis NuGet package.
Upvotes: 6