Jodrell
Jodrell

Reputation: 35706

Hello world with Expression Trees

I am trying to get to grips with Expression Trees. I thought I'd start by writing a simple helloWorld function that creates a StringBuilder, appends "Helloworld", and then outputs the string. This is what I have so far:

var stringBuilderParam = Expression.Variable
    typeof(StringBuilder), "sb");

var helloWorldBlock =
    Expression.Block( new Expression[]
        {
            Expression.Assign(
                stringBuilderParam, 
                Expression.New(typeof(StringBuilder))),
            Expression.Call(
                stringBuilderParam,
                typeof(StringBuilder).GetMethod(
                    "Append",
                    new[] { typeof(string) }),
                new Expression[]
                    {
                        Expression.Constant(
                            "Helloworld", typeof(string))
                    }),
            Expression.Call(
                stringBuilderParam,
                "ToString",
                new Type[0],
                new Expression[0])
        });

var helloWorld = Expression.Lamda<Func<string>>(helloWorldBlock).Compile();

Console.WriteLine(helloWorld);
Console.WriteLine(helloWorld());
Console.ReadKey();

The Compile() throws an InvalidOperationException

variable 'sb' of type 'System.Text.StringBuilder' referenced from scope '', but it is not defined

Obviously I'm not going about this the right way. Can someone point me in the right direction?


Obviously, I realise doing Console.WriteLine("HelloWorld"); would be somewhat simpler.

Upvotes: 3

Views: 285

Answers (1)

tukaef
tukaef

Reputation: 9214

You need to specify variables for BlockExpression in order to use them. Just call another overload:

var helloWorldBlock =
    Expression.Block(
        new ParameterExpression[] {stringBuilderParam},
        new Expression[]
            {
                Expression.Assign(
                    stringBuilderParam,
                    Expression.New(typeof (StringBuilder))),
                Expression.Call(
                    stringBuilderParam,
                    typeof (StringBuilder).GetMethod(
                        "Append",
                        new[] {typeof (string)}),
                    new Expression[]
                        {
                            Expression.Constant(
                                "Helloworld", typeof (string))
                        }),
                Expression.Call(
                    stringBuilderParam,
                    "ToString",
                    new Type[0],
                    new Expression[0])
            });

Upvotes: 3

Related Questions