tags:

views:

108

answers:

3

Hi everyone!
Is it possible to change the body of method during runtime?

class Person
{
    public void DoSth()
    { Console.WriteLine("Hello!"); }
}

I wanted to have a simple input field (like a textbox) where I can write the method body source code during runtime.

The textbox may contain data like:

for (int i = 0; i < 5; i++)
     Console.WriteLine(i);

which should be excecuted when

new Person().DoSth()

is called.

Is (or how is) this possible in C# (using Reflection)?
Thanks for your help in advance.

EDIT:
If the above isn't possible, is it possible to create a new method during runtime and call it?

+1  A: 

You cannot change a method body at runtime. There's nothing that allows you to do this. The best you could do is emit a new method.

Darin Dimitrov
At least without `dynamic`...
Steven Sudit
@Steven, how does `dynamic` allows to modify an existing type?
Darin Dimitrov
You could use an `ExpandoObject` referenced through `dynamic`, allowing you to assign a delegate so that it can be called with method syntax.
Steven Sudit
+1  A: 

It's not reflection.

Look at aspect oriented programmming that may help you getting similar results:

http://csharp-source.net/open-source/aspect-oriented-frameworks

Pierre 303
+2  A: 

Reflection.Emit is one way of generating IL at runtime... http://msdn.microsoft.com/en-us/library/8ffc3x75(v=VS.90).aspx

Lightweight code generation is another... http://blogs.msdn.com/b/joelpob/archive/2004/03/31/105282.aspx

However, neither take C# and compile it. For this you'll most likely need to invoked the C# compiler.

What is your use case (why do you want to do this)? There are security considerations with running code within your app domain, so you need to work out how you'd deal with this.

Martin Peck
I wanted to make a little developing environment for a scanner generator. The genertor produces a C# method, which should be excecuted whenever a token is found. The transition tables can be actually loaded during runtime (the are stored in file). I simply don't want to recompile the hole scanner program while developing the scanner specification.
youllknow