Yechiel B.D.
Yechiel B.D.

Reputation: 2109

How to use CodeDom to generate inline dynamic methods?

I have a CodeMethodInvokeExpression which i wish to use as ()=><[function call]>.

E.g.: Task.Run(()=><[My CodeMethodInvokeExpression]>).

And just to be clear, CodeMethodInvokeExpression can be very complex, such as a call to a generic method with out and ref pramaeters, so trying to write something which parses it, may be very complicated.

So the questions are:

  1. Might there be a CodeDom way of doing this?
  2. Might there be a CodeDom way of getting the string representation of CodeMethodInvokeExpression so I could use it as a CodeSnippetExpression.

Upvotes: 1

Views: 367

Answers (1)

Luaan
Luaan

Reputation: 63742

CodeDom is kind of obsolete. As far as a I know, the best you can do is using CodeSnippetExpression, but by the time you have CodeMethodInvokeExpression, it's too late - you don't really have information about the method you're trying to call, just about it's name, object and arguments. Not to mention that it kind of defeats the purpose of using CodeDom in the first place.

Of course, you're generating code, so you could just create the anonymous method yourself, that's what the compiler does anyway. But again, you'll need more information than what you're getting in the CodeMethodInvokeExpression. In the end, you're just going in circles.

Also, note that out is C#'s speciality - it's not actually something common to CLR languages. In other languages, it might just be the same as ref.

Note that you can use CodeDom to generate code snippets:

var provider = new CSharpCodeProvider();

using (var writer = new StringWriter())
{
    provider.GenerateCodeFromExpression
        (
            new CodeMethodInvokeExpression
            (
                new CodeMethodReferenceExpression
                (
                    new CodeThisReferenceExpression(), 
                    "MyMethod", 
                    new CodeTypeReference(typeof(string))
                ),
                new CodeDirectionExpression(FieldDirection.Out, new CodeArgumentReferenceExpression("myArgument"))
            ),
            writer,
            null
        );

    writer.ToString().Dump();
}

This sample code will then generate this:

this.MyMethod(out myArgument)

You can create a CodeSnippetExpression out of that, prepending the () => manually, and use that snippet as an argument to your method taking a delegate. Again, this will only work for C# - you'll need to modify the code to make it work elsewhere.

Upvotes: 1

Related Questions