Iulian Radulescu
Iulian Radulescu

Reputation: 324

Expression.Block method gives different errors in c#

Let us have the following:

Func<string, int> counterOfChar = (myString) => {
         Console.WriteLine("Here is my parameter "+myString); 
         return myString.Count();
};

I want to bring all expressions involved here , by defining them so:

Expression<Action<string>> first = (param) => Console.WriteLine("Here is my parameter "+param);
Expression<Func<string, int>> second = (param) => param.Count();

And then call Expression.Block(first, second); as an example .

I am struggling for a week now and I don't want to tell you how diverse are the errors received until this moment. Can someone write the corresponding Block and lambda expression for the delegate, but not going deep into ex: Method.Call ? Just stick to expressions !?

Thank you!

Upvotes: 0

Views: 617

Answers (1)

xanatos
xanatos

Reputation: 111870

Expression<Action<string>> first = (param) => Console.WriteLine("Here is my parameter " + param);
Expression<Func<string, int>> second = (param) => param.Length; // .Count() is useless here!

Expression<Func<string, int>> third = 
    Expression.Lambda<Func<string, int>>(
         Expression.Block(first.Body, 
                          Expression.Invoke(second, first.Parameters[0])), 
         first.Parameters[0]);

var f = third.Compile();
var r1 = f("Hello");

"merging" two Expressions is always a little complex, because the two param of the two expressions are "different". They aren't the same param (it's like one is param1 and the other is param2). Here we resolve it by reusing the first parameter of the first expression as the parameter of the "new" expression and Expression.Invoke the other expression.

Without cheating, we could have

var par = Expression.Parameter(typeof(string));

Expression<Func<string, int>> third = 
    Expression.Lambda<Func<string, int>>(
        Expression.Block(
            Expression.Invoke(first, par), 
            Expression.Invoke(second, par)), 
        par);

var f = third.Compile();
var r1 = f("Hello");

where we introduce a new parameter par and we Expression.Invoke the other two expressions.

Note that Entity Framework doesn't support Expression.Invoke. In this case you can use a parameter rewriter (something like this.)

Upvotes: 2

Related Questions