user725913
user725913

Reputation:

Call method from an outside class using CodeDom

I have two methods; one of which resides outside of a class, the other inside a class. I would like to be able to use CodeDom to make a call from the method outside of the class, to the one inside of the class. This will be much easier to explain through the use of code...

Class with method inside:

public static class Public
{
    public static byte[] ReadAllData(string sFilePath)
    {
        byte[] b = new byte[sFilePath.Length];
        b = System.IO.File.ReadAllBytes(sFilePath);
        return b;
    }  
}

** from another class:

Public.ReadAllData(@"C:\File.exe");

I want to recreate the above using CodeDom -

CodeMemberMethod method = new CodeMemberMethod();

method.Statements.Add(new CodePropertyReferenceExpression(
new CodeVariableExpression("Public"), "ReadAllData"));

The above code will produce the following output - but notice I was not able to pass any parameters!

Public.ReadAllData;

Upvotes: 2

Views: 3968

Answers (2)

svick
svick

Reputation: 244848

var compiler = new CSharpCodeProvider();

var invocation = new CodeMethodInvokeExpression(
    new CodeTypeReferenceExpression(typeof(Public)),
    "ReadAllData", new CodePrimitiveExpression(@"C:\File.exe"));

var stringWriter = new StringWriter();
compiler.GenerateCodeFromExpression(invocation, stringWriter, null);
Console.WriteLine(stringWriter.ToString());

This code produces the result

ConsoleApplication1.Public.ReadAllData("C:\\File.exe")

Another option is

var invocation = new CodeMethodInvokeExpression(
    new CodeMethodReferenceExpression(
        new CodeTypeReferenceExpression(typeof(Public)),"ReadAllData"),
    new CodePrimitiveExpression(@"C:\File.exe"));

Using CodeMethodReferenceExpression this way could be useful when calling generic methods: you can specify type parameters in its constructor.

Upvotes: 8

ckramer
ckramer

Reputation: 9443

I've only used CodeDom a bit, but I think you'll want the CodeMethodInvokeExpression, instead of CodePropertyReferenceExpression. It looks like CodePropertyReferenceExpression is generating a statement that is accessing a property value, rather than invoking a method.

There is a Parameters property on CodeMethodInvokeExpression that will allow you to specify the parameters to pass to the method you are wanting to invoke.

Upvotes: 0

Related Questions