Search code examples
.netexpression-trees

How do I specify the object to return from an expression tree method?


I'm trying to create a method using an expression tree that returns an object, but I can't figure out how to actually specify the object to return. I've tried reading this, but the return value doesn't actually seem to be specified anywhere.

I've got all the assignments & stuff down, but how do I specify the object to return from a method created using expression trees?

EDIT: these are v4 expression trees, and the method I'm trying to create does something like this:

private object ReadStruct(BinaryReader reader) {
    StructType obj = new StructType();
    obj.Field1 = reader.ReadSomething();
    obj.Field2 = reader.ReadSomething();
    //...more...
    return obj;
}

Solution

  • Apparently a return is a GotoExpression that you can create with the Expression.Return factory method. You need to create a label at the end to jump to it. Something like this:

    // an expression representing the obj variable
    ParameterExpression objExpression = ...;
    
    LabelTarget returnTarget = Expression.Label(typeof(StructType));
    
    GotoExpression returnExpression = Expression.Return(returnTarget, 
        objExpression, typeof(StructType));
    
    LabelExpression returnLabel = Expression.Label(returnTarget, defaultValue);
    
    BlockExpression block = Expression.Block(
        /* ... variables, all the other lines and... */,
        returnExpression,
        returnLabel);
    

    The types of the label target and the goto expression must match. Because the label target has a type, the label expression must have a default value.