Budi Hartanto
Budi Hartanto

Reputation: 347

Roslyn: Get the array value

I try to get the array value using Roslyn. For example, if I have a C# code like this:

int[] arrInt = {10, 20, 30, 40, 50};

then how can I get the information that arrInt[0] is 10, arrInt[1] is 20, and so on.

Upvotes: 2

Views: 1361

Answers (1)

tenor
tenor

Reputation: 1105

I'd encourage you to check the documentation, FAQ and samples, especially the sections on syntax and semantic analysis.

Here's the solution:

static void Main(string[] args)
{
    string code = "int[] arrInt = {10, 20, 30, 40, 50};";

    //Parse Syntax tree
    var tree = Roslyn.Compilers.CSharp.SyntaxTree.ParseText(code);

    //Locate the arrInt identifier in the Syntax tree
    var declarator = tree.GetRoot().DescendantNodesAndSelf().Where(t => t.Kind == Roslyn.Compilers.CSharp.SyntaxKind.VariableDeclarator
        && ((Roslyn.Compilers.CSharp.VariableDeclaratorSyntax)t).Identifier.ValueText == "arrInt").First() as Roslyn.Compilers.CSharp.VariableDeclaratorSyntax;

    var index = 1;
    var expression = GetExpressionAtInitializer(declarator, index);

    Console.WriteLine(expression);

    //Examine 'expression' for more information on value at the second index            
}

private static Roslyn.Compilers.CSharp.ExpressionSyntax GetExpressionAtInitializer(Roslyn.Compilers.CSharp.VariableDeclaratorSyntax declarator, int index)
{
    var initializerExpression = declarator.Initializer.Value as Roslyn.Compilers.CSharp.InitializerExpressionSyntax;
    var expression = initializerExpression.Expressions[index];
    return expression;
}

You can use VS's quick watch window to view the hierarchy of the syntax tree.

You might be able to get more meaningful information on the symbols in your code if you apply some semantic analysis to it.

Upvotes: 5

Related Questions