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.

Answers


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.


Need Your Help

Use cases where PendingIntent is used

android android-pendingintent

I am trying to see how PendingIntents are useful. Can you provide examples of apps where PendingIntents are used?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.