Click to See Complete Forum and Search --> : Create dynamic code


Otex
February 20th, 2009, 02:54 AM
Hi,
I am not sure how to explain this, I'd like to have some code dynamically created at execution in my program.
Maybe if I put some non working code it would give a better idea


int a = 1;
int b = 2;
string myLogic = "a + b";

int c = myMethod(myLogic);
// c would be 3
// of course if myLogic was "a * b", c would be 2 etc..

public int myMethod(string logic)
{

int result;
..
..
..
return (result);
}



In other words I'd like to convert my string to code.

I suspect maybe invokemember or delegates may help me but I cant work it out.
Any help appreciated

boudino
February 20th, 2009, 04:18 AM
Let's inspire:

string src =
@"using System;

namespace Test{
public class TestClass {

public TestClass() {}
}
}";

CodeDomProvider cdp = CodeDomProvider.CreateProvider("cs");
CompilerResults r = cdp.CompileAssemblyFromSource(
new CompilerParameters
{
GenerateExecutable = false,
IncludeDebugInformation = true,
GenerateInMemory = true,
ReferencedAssemblies = {"YourAssembly.dll"},
},
src);

Type t = r.CompiledAssembly.GetType("Test.TestClass");
object tInstance = Activator.CreateInstance(t);

Otex
February 20th, 2009, 06:50 AM
Thanks, I played with it a bit and it works, however it seems there is an issue.
Every time it runs it takes some memory and it does not release it.

Perhaps I'll explain what I want to do, maybe there is a better way to achieve it.

I have a program where the users must be able to enter some enter some relatively simple logic that is being processed via a form.

Basically I have 4 variables for which the user enters a limit and a simple AND OR logic and some brackets.
This will then be interpreted (or compiled) by the program and used later on.

There is a main menu with a button that launches a form to enter the logic then another button that executes the methods that at some stage use the logic that was entered.

Once entered the logic is quite static it may only be changed now and then when some changes are needed.

Would it be better if the logic is stored in a dll and used by the other method ?
I assume the dll's are loaded when the app starts ? if so can I reload it when it is changed ?

Or is there a better way to do it ?

Thanks