Question

Ist it possible to generate c# code like this with System.CodeDom?

public MyClass() // ctor
{
    Foo().Bar();
}

I only get the following code blocks

public MyClass() // ctor
{
    Foo(Bar());
}


public MyClass() // ctor
{
    Foo();
    Bar();
}
Was it helpful?

Solution

Yes, of course. See the constructor for CodeMethodInvokeExpression:

public CodeMethodInvokeExpression(
    CodeExpression targetObject,
    string methodName,
    params CodeExpression[] parameters
)

That first parameter, the targetObject, can itself be any expression1 whose result is a object, including another method invoke expression. So, once you've created the expression that represents invoking Foo(), you would do:

booInvokeExpression = new CodeMethodInvokeExpression(fooInvokeExpression,"Boo");

1I originally had the weasel-eze "Just about" in this sentence, but I can't really think of any counter examples. If you've got one, feel free to let me know in the comments

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top