0

I am trying to develop a template engine in c# and in my concept I will need to read to read methods as well as parameters from text files.This shows something could be done , but it does not work if the parameter is also read from the text.Is there a way to achieve this?

        private static void Main(string[] args)
        {
            string returnValue = Execute("AMethod(\"Hello\")");
            //the result in retunValue is same as from code commented below:
            // string returnValue= AMethod("Hello");
        }

        public static string AMethod(string parameter)
        {
            return "xyz" + parameter;
        }

The problem here is how to write the Execute Method

Community
  • 1
  • 1
Thunder
  • 10,366
  • 25
  • 84
  • 114

2 Answers2

1

The link you provided has the answer you are looking for. Look at the line

object[] parametersArray = new object[] { "Hello" }; and change it to

object[] parametersArray = new object[] { parameter };

XtremeBytes
  • 1,469
  • 8
  • 12
0

There are really 3 ways to accomplish what you are trying to accomplish:

  1. Reflection (this is what is explained in the article you reference)
  2. Reflection.Emit
  3. Dynamic compilation

2 & 3 are more complicated and heavy weight, but depending on the syntax you are trying to achieve in your template engine, one of those might be the best way to go. Reflection requires that you handle each aspect of the invocation--binding to the correct method, passing arguments as arrays, etc. Dynamic compilation would allow you to take a line a C# code formatted exactly how you would write it in a .cs file, compile it to a new method, load the assembly, and execute it. This is all a bit of a hassle, so if you aren't married to having to execute a string that looks like AMethod("Hello"), I highly recommend the reflection route.

Here is an example of what you are trying to achieve with pure reflection:

    private static void Main(string[] args)
    {
        string methodName = "AMethod";
        object[] parameters = new object [] {"Hello", "foo"};
        MethodInfo method = typeof(Program).GetMethod(methodName, BindingFlags.Static);
        string returnValue = (string)method.Invoke(null, parameters);
    }

    public static string AMethod(string parameter1, string parameter2)
    {
        return "xyz" + parameter1 + "abc" + parameter2;
    }

For examples of 2 & 3, you can take a look at this question: Compiling code dynamically using C#

Community
  • 1
  • 1
mikdav
  • 96
  • 3