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 8745639
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T12:03:58+00:00 2026-06-13T12:03:58+00:00

I am currently trying to write some code which turns C# Expressions into text.

  • 0

I am currently trying to write some code which turns C# Expressions into text.

To do this, I need to not only walk through the Expression tree, but also evaluate just a little part of it – in order to get the current value of a local variable.

I am finding very hard to put into words, so here is the pseudo-code instead. The missing part is in the first method:

public class Program
{
    private static void DumpExpression(Expression expression)
    {
        // how do I dump out here some text like:
        //      set T2 = Perform "ExternalCalc" on input.T1
        // I can easily get to:
        //      set T2 = Perform "Invoke" on input.T1
        // but how can I substitute Invoke with the runtime value "ExternalCalc"?
    }

    static void Main(string[] args)
    {
        var myEvaluator = new Evaluator() {Name = "ExternalCalc"};
        Expression<Func<Input, Output>> myExpression = (input) => new Output() {T2 = myEvaluator.Invoke(input.T1)};

        DumpExpression(myExpression);
    }
}

class Evaluator
{
    public string Name { get; set; }  

    public string Invoke(string input)
    {
        throw new NotImplementedException("Never intended to be implemented");
    }
}

class Input
{
    public string T1 { get; set; }
}

class Output
{
    public string T2 { get; set; }
}

I have started investigating this using code like:

        foreach (MemberAssignment memberAssignment in body.Bindings)
        {
            Console.WriteLine("assign to {0}", memberAssignment.Member);
            Console.WriteLine("assign to {0}", memberAssignment.BindingType);
            Console.WriteLine("assign to {0}", memberAssignment.Expression);

            var expression = memberAssignment.Expression;
            if (expression is MethodCallExpression)
            {       
                var methodCall = expression as MethodCallExpression;
                Console.WriteLine("METHOD CALL: " + methodCall.Method.Name);
                Console.WriteLine("METHOD CALL: " + expression.Type.Name);
                var target = methodCall.Object;

                // ?
            }
        }

but once I get to that MethodCallExpression level then I am feeling a bit lost about how to parse it and to then get the actual instance.

Any pointers/suggestions on how to do this very much appreciated.

  • 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-13T12:03:59+00:00Added an answer on June 13, 2026 at 12:03 pm

    Parsing expression trees is… complex and time-consuming. Here’s a very incomplete version that just-about handles your example. In particular, note that we need to:

    • hard-code to Evaluator, since “ExternalCalc” is not part of the expression
    • manually evaluate some of the tree

    Output:

    a new Output set T2 to: call ExternalCalc on get myEvaluator from capture-context with input = get T1 from @input

    Code:

    private static void DumpExpression(Expression expression)
    {
        var sb = new StringBuilder();
        Walk(expression, sb);
        string s = sb.ToString();      
    }
    static object Evaluate(Expression expr)
    {
        switch (expr.NodeType)
        {
            case ExpressionType.Constant:
                return ((ConstantExpression)expr).Value;
            case ExpressionType.MemberAccess:
                var me = (MemberExpression)expr;
                object target = Evaluate(me.Expression);
                switch (me.Member.MemberType)
                {
                    case System.Reflection.MemberTypes.Field:
                        return ((FieldInfo)me.Member).GetValue(target);
                    case System.Reflection.MemberTypes.Property:
                        return ((PropertyInfo)me.Member).GetValue(target, null);
                    default:
                        throw new NotSupportedException(me.Member.MemberType.ToString());
                }
            default:
                throw new NotSupportedException(expr.NodeType.ToString());
        }
    }
    static void Walk(Expression expr, StringBuilder output)
    {
        switch (expr.NodeType)
        {
            case ExpressionType.New:
                var ne = (NewExpression)expr;
                var ctor = ne.Constructor;
                output.Append(" a new ").Append(ctor.DeclaringType.Name);
                if(ne.Arguments != null && ne.Arguments.Count != 0)
                {
                    var parameters = ctor.GetParameters();
                    for(int i = 0 ;i < ne.Arguments.Count ; i++)
                    {
                        output.Append(i == 0 ? " with " : ", ")
                              .Append(parameters[i].Name).Append(" =");
                        Walk(ne.Arguments[i], output);
                    }                    
                }
                break;
            case ExpressionType.Lambda:
                Walk(((LambdaExpression)expr).Body, output);
                break;
            case ExpressionType.Call:
                var mce = (MethodCallExpression)expr;
    
                if (mce.Method.DeclaringType == typeof(Evaluator))
                {
                    object target = Evaluate(mce.Object);
                    output.Append(" call ").Append(((Evaluator)target).Name);
                }
                else
                {
                    output.Append(" call ").Append(mce.Method.Name);
                }
                if (mce.Object != null)
                {
                    output.Append(" on");
                    Walk(mce.Object, output);
                }
                if (mce.Arguments != null && mce.Arguments.Count != 0)
                {
                    var parameters = mce.Method.GetParameters();
                    for (int i = 0; i < mce.Arguments.Count; i++)
                    {
                        output.Append(i == 0 ? " with " : ", ")
                                .Append(parameters[i].Name).Append(" =");
                        Walk(mce.Arguments[i], output);
                    }
                }
                break;
            case ExpressionType.MemberInit:
                var mei = (MemberInitExpression)expr;
                Walk(mei.NewExpression, output);
                foreach (var member in mei.Bindings)
                {
                    switch(member.BindingType) {
                        case MemberBindingType.Assignment:
                            output.Append(" set ").Append(member.Member.Name)
                                .Append(" to:");
                            Walk(((MemberAssignment)member).Expression, output);
                            break;
                        default:
                            throw new NotSupportedException(member.BindingType.ToString());
                    }
    
                }
                break;
            case ExpressionType.Constant:
                var ce = (ConstantExpression)expr;
                if (Attribute.IsDefined(ce.Type, typeof(CompilerGeneratedAttribute)))
                {
                    output.Append(" capture-context");
                }
                else
                {
                    output.Append(" ").Append(((ConstantExpression)expr).Value);
                }
                break;
            case ExpressionType.MemberAccess:
                var me = (MemberExpression)expr;
                output.Append(" get ").Append(me.Member.Name).Append(" from");
                if (me.Expression == null)
                { // static
                    output.Append(me.Member.DeclaringType.Name);
                }
                else
                {
                    Walk(me.Expression, output);
                }
                break;
            case ExpressionType.Parameter:
                var pe = (ParameterExpression)expr;
                output.Append(" @").Append(pe.Name);
                break;
            default:
                throw new NotSupportedException(expr.NodeType.ToString());
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am currently trying to write some code to show some text using DirectX
I am currently trying to write some code which is going to send a
I am currently trying to write some code that will accept some FTP details,
I am currently trying to write functional tests for a charging form which gets
I'm trying to extract text from arbitrary html pages. Some of the pages (which
I am currently trying to write some flexible compile time mathematics library and just
I'm trying to write a perl script that determines which users are currently logged
I am trying to write some javascript which asks a user, when they leave
I'm currently trying to understand some assembler code well enough to reconstruct the C
I'm trying to write some XSLT which basically should go through the following algorithm:

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.