Willem van Hooijdonk
Willem van Hooijdonk

Reputation: 95

Is there a way to generate a local method within another method in CodeDom?

I'm creating code by using CodeDom. However, CodeDom does not support lambda statements. So I'm now trying to mimic a lambda statement by creating a local method and pass on the method as a parameter to another method. Like so:

public string MainMethod(string myParameter)
{
    string g() { return instance.MainMethod(myParameter); }
    return someOtherMethod(g);
}

The method 'MainMethod' is already generated by using CodeDom and I'm trying to get the local method in there. However, I cannot find a way to do that up to this point. I could use some help with that.

I already tried adding a CodeMemberMethod to a CodeMemberMethod but there seems to be no way to do that. I cannot seem to find any alternatives.

Currently my CodeDom code is using MethodInfo as a base:

var method = new CodeMemberMethod();
method.Name = methodInfo.Name;
method.ReturnType = new CodeTypeReference(methodInfo.ReturnType);

//left out parameter stuff

var gMethod = new CodeMemberMethod() { Name = "g", ReturnType = new CodeTypeReference(methodInfo.ReturnType) };
gMethod.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("instance"), methodInfo.Name), parameterReferences.ToArray())));
method.Statements.Add(gMethod);

Now, the pain is in the last statement. I'm actually trying to add a CodeMemberMethod to a CodeMemberMethod, which is not allowed via the Statements property. Is there any way to do that in another way?

Upvotes: 0

Views: 292

Answers (1)

Ondrej Tucny
Ondrej Tucny

Reputation: 27964

Local functions were not a supported language construct until C# version 7. CodeDOM was designed much earlier and does not cover all C# feature, even of the then-current version of C#. In other words, there is, unfortunately, no way to declare a “local method” and add it to the Statements collection of another method.

Instead, consider declaring a separate private method. Your class's public interface will remain unaffected and, most likely, you will achieve what you want. However, no implicit access to the 'outer method's' parameters will be possible.

Also, consider looking at this answer for further ideas.

Upvotes: 3

Related Questions