Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7971949
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T07:44:40+00:00 2026-06-04T07:44:40+00:00

I am creating expression tree and there is a situation where I need to

  • 0

I am creating expression tree and there is a situation where I need to create one lambda in another lambda and store inner one in a class and add that class in expression tree.
This is simple example of what I am trying to do (this code does not compile):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace SimpleTest {
    public class LambdaWrapper {
        private Delegate compiledLambda;
        public LambdaWrapper(Delegate compiledLambda) {
            this.compiledLambda = compiledLambda;
        }
        public dynamic Execute() {
            return compiledLambda.DynamicInvoke();
        }
    }

    public class ForSO {

        public ParameterExpression Param;

        public LambdaExpression GetOuterLambda() {
            IList<Expression> lambdaBody = new List<Expression>();
            Param = Expression.Parameter(typeof(object), "Param");
            lambdaBody.Add(Expression.Assign(
                            Param, 
                            Expression.Constant("Value of 'param' valiable"))
                          );

            lambdaBody.Add(Expression.Call(
                            null, 
                            typeof(ForSO).GetMethod("Write"), 
                            Param)
                          );

            Delegate compiledInnerLambda = GetInnerLambda().Compile();
            LambdaWrapper wrapper = new LambdaWrapper(compiledInnerLambda);
            lambdaBody.Add(Expression.Constant(wrapper));
            //lambdaBody.Add(GetInnerLambda());
            return Expression.Lambda(
                        Expression.Block(
                                new ParameterExpression[] { Param }, 
                                lambdaBody));
        }

        public LambdaExpression GetInnerLambda() {
            return Expression.Lambda(
                    Expression.Block(
                        Expression.Call(null, 
                                typeof(ForSO).GetMethod("Write"), 
                                Expression.Constant("Inner lambda start")),
                        Expression.Call(null, 
                                typeof(ForSO).GetMethod("Write"), 
                                Param),
                        Expression.Call(null, 
                                typeof(ForSO).GetMethod("Write"), 
                                Expression.Constant("Inner lambda end"))
                    )
                );
        }

        public static void Write(object toWrite) {
            Console.WriteLine(toWrite);
        }

        public static void Main(string[] args) {
            ForSO so = new ForSO();
            LambdaWrapper wrapper = so.GetOuterLambda().Compile()
                                      .DynamicInvoke() as LambdaWrapper;
            wrapper.Execute();
            //(so.GetOuterLambda().Compile().DynamicInvoke() as Delegate).DynamicInvoke();
        }
    }
}

Problem is in GetInnerLambda().Compile() line in GetOuterLambda method.
I am aware of one solution – it is in commented part of code. With that, everything works fine, but I need a wrapper as return value, not expression subtree (it might be ok to store inner lambda subtree in LambdaWrapper, and compile it later, but same problem occures).

Error I am getting is Unhandled Exception: System.InvalidOperationException: variable 'Param' of type 'System.Object' referenced from scope '', but it is not defined.

If I add Param to block variables in inner lambda, code compiles, but Param has not value assigned in outer lambda (and that makes sense).

How can this be solved?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T07:44:42+00:00Added an answer on June 4, 2026 at 7:44 am

    With help from Balazs Tihanyi I found solution that works for me exactly as I need it. It is a bit more work because I had to create binders, but I my main project I already had them, so I created dummy binders for this example to work.

    This is my final solution:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Dynamic;
    
    
    namespace SimpleTest {
        public class MyCreateBinder : CreateInstanceBinder {
            public MyCreateBinder(CallInfo info) : base(info) { }
    
            public override DynamicMetaObject FallbackCreateInstance(
                                            DynamicMetaObject target,
                                            DynamicMetaObject[] args,
                                            DynamicMetaObject errorSuggestion) {
                var param = args[0].Value;
    
                Type toCreate = target.Value as Type;
                var ctors = toCreate.GetConstructors()
                            .Where(c => c.GetParameters().Length == args.Length)
                            .ToArray();
    
                if (ctors.Length == 0)
                    throw 
                        new Exception(
                          String.Format(
                          "Can not find constructor for '{0}' with {1} parameters",
                          toCreate, args.Length));
                ConstructorInfo ctorToUse = ctors[0];
                return new DynamicMetaObject(
                                Expression.New(
                                    ctorToUse,
                                    args.Select(a => a.Expression).ToList()),
                           BindingRestrictions.Empty);
            }
        }
    
        public class MySetMemberBinder : SetMemberBinder {
    
            public MySetMemberBinder(string name) : base(name, false) { }
    
            public override DynamicMetaObject FallbackSetMember(
                                    DynamicMetaObject target,
                                    DynamicMetaObject value,
                                    DynamicMetaObject errorSuggestion) {
    
                throw new NotImplementedException();
            }
        }
    
        public class MyGetMemberBinder : GetMemberBinder {
            public MyGetMemberBinder(string name) : base(name, false) { }
    
            public override DynamicMetaObject FallbackGetMember(
                                            DynamicMetaObject target,
                                            DynamicMetaObject errorSuggestion) {
                throw new NotImplementedException();
            }
        }
    
        public class MyInvokeMemberBinder : InvokeMemberBinder {
            public MyInvokeMemberBinder(string name, CallInfo callInfo) 
                : base(name, false, callInfo) { }
    
            public override DynamicMetaObject FallbackInvokeMember(
                                        DynamicMetaObject target,
                                        DynamicMetaObject[] args,
                                        DynamicMetaObject errorSuggestion) {
                var a = this;
                throw new NotImplementedException();
            }
    
            public override DynamicMetaObject FallbackInvoke(
                                        DynamicMetaObject target,
                                        DynamicMetaObject[] args,
                                        DynamicMetaObject errorSuggestion) {
                throw new NotImplementedException();
            }
        }
    
        public class LambdaWrapper : IDynamicMetaObjectProvider {
            private Delegate compiledLambda;
            private LambdaExpression exp;
    
            public LambdaWrapper(LambdaExpression exp) {
                this.exp = exp;
                this.compiledLambda = exp.Compile();
            }
            public dynamic Execute(dynamic param) {
                return compiledLambda.DynamicInvoke(param);
            }
    
            public DynamicMetaObject GetMetaObject(Expression parameter) {
                return new MetaLambdaWrapper(parameter, this);
            }
        }
    
        public class MetaLambdaWrapper : DynamicMetaObject {
            public MetaLambdaWrapper(Expression parameter, object value) : 
                base(parameter, BindingRestrictions.Empty, value) { }
    
            public override DynamicMetaObject BindInvokeMember(
                                        InvokeMemberBinder binder,
                                        DynamicMetaObject[] args) {
                MethodInfo method = this.Value.GetType().GetMethod(binder.Name);
                return new DynamicMetaObject(
                            Expression.Call(
                                Expression.Constant(this.Value),
                                    method,
                                        args.Select(a => a.Expression)),
                            BindingRestrictions.GetTypeRestriction(
                                this.Expression, 
                                typeof(LambdaWrapper)));
            }
        }
    
    
        public class ForSO {
            public ParameterExpression Param;
            public LambdaExpression GetOuterLambda() {
                Expression wrapper;
                IList<Expression> lambdaBody = new List<Expression>();
                Param = Expression.Parameter(typeof(object), "Param");
                lambdaBody.Add(Expression.Assign(
                                Param,
                                Expression.Constant("Value of 'param' variable"))
                              );
                lambdaBody.Add(Expression.Call(
                                null,
                                typeof(ForSO).GetMethod("Write"),
                                Param)
                              );
    
                wrapper = Expression.Dynamic(
                                    new MyCreateBinder(new CallInfo(1)),
                                    typeof(object),
                                    Expression.Constant(typeof(LambdaWrapper)),
                                    Expression.Quote(GetInnerLambda()));
    
    
                lambdaBody.Add(
                    Expression.Dynamic(
                        new MyInvokeMemberBinder("Execute", new CallInfo(1)),
                        typeof(object),
                        wrapper,
                    Expression.Constant("calling inner lambda from outer")));
    
                lambdaBody.Add(wrapper);
    
                return Expression.Lambda(
                            Expression.Block(
                                    new ParameterExpression[] { Param },
                                    lambdaBody));
            }
    
            public LambdaExpression GetInnerLambda() {
                ParameterExpression innerParam = Expression.Parameter(
                                                    typeof(object), 
                                                    "innerParam");
                return Expression.Lambda(
                        Expression.Block(
                            Expression.Call(null,
                                    typeof(ForSO).GetMethod("Write"),
                                    Expression.Constant("Inner lambda start")),
                            Expression.Call(null,
                                    typeof(ForSO).GetMethod("Write"),
                                    innerParam),
                            Expression.Call(null,
                                    typeof(ForSO).GetMethod("Write"),
                                    Param),
                            Expression.Call(null,
                                    typeof(ForSO).GetMethod("Write"),
                                    Expression.Constant("Inner lambda end"))
                        ),
                        innerParam
                    );
            }
    
            public static void Write(object toWrite) {
                Console.WriteLine(toWrite);
            }
    
            public static void Main(string[] args) {
                Console.WriteLine("-----------------------------------");
                ForSO so = new ForSO();
    
                LambdaWrapper wrapper = (LambdaWrapper) so.GetOuterLambda()
                                                        .Compile()
                                                        .DynamicInvoke();
                Console.WriteLine("-----------------------------------");
                wrapper.Execute("Calling from main");
            }
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm creating an expression tree manually like this var innerAddition = Expression.Add(Expression.Constant(5), Expression.Constant(9)); var
I'm creating a CSS editor and am trying to create a regular expression that
I need help creating a regular expression that will parse the following string :
When creating a lambda expression by hand I get a 'Parameter not in scope'
I need help creating a regular expression for redirecting my old URL's to new
can any one help me in creating a regular expression for password validation. The
How should I go about creating a cron expression that will fire every 90
I am looking for help in creating a Regular Expression that validates a URL
I have the following criteria for creating a regular expression for a password that
I am creating Linq expression trees from F# that operates on a custom datatype

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.