2

I have a C# application, and I want to run a function which is defined in text to take one parameter of class A and return a double.

Parameter "A" will be some structured data, and the function will be a formula upon A.

(Imagine A had properties num1, num2, and one formula was defined to return the average, another arbitrarily to return num1 * 2).

As such, I want to load my function definition from a text source, compile them in some manner, and execute them.

In terms of the structure of the code, I do suppose I could inject the body of the function to be a member function of an arbitrary class, or if I can compile a delegate and then execute it passing a parameter context that would be sufficient also.

What is the way to go about this?

2
  • I think you need to specify which version of C# you're using. The newer versions can do this more easily than the older ones. Commented Jul 9, 2009 at 13:08
  • old .NET 1.1 version unfortunately. Commented Jul 9, 2009 at 13:11

5 Answers 5

3

Use the .Net CodeDOM to compile C# On the Fly

Sign up to request clarification or add additional context in comments.

1 Comment

CodeDom is great for this type of problem. However, if you find yourself needing to use some more advanced features of C# that CodeDom doesn't support, you should consider using Reflection.Emit.
1

I would suggest using an expression parser where you can enter an excel like expression, and includes all basic functions (statistical, string manipulation, math/trig). I've used CalcEngine for a similar requirement with good results. You can extend it with custom functions.

Comments

0

You might want to have a look at the c# code dom. You could use this to dynamically write and compile C# code, then execute it.

Beware that this is a very high risk operation so be careful. Still its cool functionality to have in the environment.

Comments

0

There is documentation on how to compile the C# code here.

Once you have it compiled your are going to need to use reflection to invoke the method (provided its static)

If you want to inject it on to an existing class with LCG you will need to use IL.

Comments

0

Another approach to doing this is to use the DynamicMethod class. Though this requires a knowledge of IL to do so.

I'd assume this would be quicker though to compile at runtime.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.