Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection, changing a method's body

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?

like image 423
raisyn Avatar asked Sep 05 '10 08:09

raisyn


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


1 Answers

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.

like image 54
Martin Peck Avatar answered Sep 30 '22 00:09

Martin Peck