Roslyn fluent syntax to create expression tree for multiline lambda

.net c# expression-trees metaprogramming roslyn


I am writing a Roslyn-based custom tool that tries to eradicate CS0834 by rewriting given multi-line lambdas into Expression trees at build time.

Edit: At this time, I am only targeting anonymous multiline lambdas.

For example:

    // Will produce CS0834 if Bar takes Expression<Action<...>>
    Foo.Bar((int x) => { ... });



So that will compile correctly. While I can figure out the Expression.(blah) syntax required to convert the given code, doing it using Roslyn is another matter altogether. Perhaps I just don't know the Roslyn Syntax.(blah) API well enough to translate this raw lambda

    (int index, float[] a, float[] b) =>
        var sum = 0f;
        for (int i = 0; i < index; i++)
            sum += a[i];

        b[index] = sum;

Could someone help me write the Roslyn Syntax.(blah) syntax that will generate an expression tree that looks like the one below?

    Expression<Action<int, float[], float[]>> action = 
                Expression.Assign(sumParameter, Expression.Constant(0)),
                Expression.Loop(...) // The for loop here

Once I have a starting point - I ought to be able to figure out or at least get started translating simple cases in this project.

Many thanks, your help is much appreciated.

9/19/2012 4:08:41 PM

Accepted Answer

We have a tool called Quoter that will generate Syntax.* API calls for any C# program.

You can view it live at

If you figure out the logic to generate the Expression.* calls, you can easily generate code that generates it.

Update: the tool is now open-source!

12/21/2014 6:28:01 AM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow