Creating a function dynamically at run-time

You have several ways how to do it:

  • dynamically create lambda expression (look at Dynamic LINQ: Part 1)
  • dynamically create CodeDom model and compile it at run-time (look at CodeDom.Compiler namespace
  • dynamically create C#/VB.NET source code and compile it at run-time (look at CSharpCodeProvider and VBCodeProvider classes )
  • dynamically create object model, which can do same things like the method (look at Strategy Design Pattern

The easiest way to do it is probably DLINQ as TcKs suggested.

The fastest (I believe, in 3.5) is to create a DynamicMethod. Its also the scariest method as well. You're essentially building a method using IL, which has about the same feel as writing code in machine language.

I needed to do this to dynamically attach event handlers in some thing or another (well, I didn't need to do it, I just wanted to make unit testing events easier). It seemed a bit daunting at the time because I don't know crap about IL, but I figured out a simple way to accomplish this.

What you do is create a method that does exactly what you want. The more compact the better. I'd provide an example if I could figure out exactly what you're trying to do. You write this method in a class within a DLL project and compile it in release mode. Then you open the DLL in Reflector and disassemble your method. Reflector gives you the option of what language you wish to disassemble to--select IL. You now have the exact calls you need to add to your dynamic method. Just follow the example on MSDN, switching out the example's IL for your reflected methods' code.

Dynamic methods, once constructed, invoke at about the same speed as compiled methods (saw a test where dynamic methods could be called in ~20ms where reflection took over 200ms).


Your question is pretty unclear, but you can certainly use expression trees to create delegates dynamically at execution time. (There are other ways of doing it such as CodeDOM, but expression trees are handier if they do all you need. There are significant restrictions to what you can do, however.)

It's often easier to use a lambda expression with some captured variables though.

For example, to create a function which will add the specified amount to any integer, you could write:

static Func<int, int> CreateAdder(int amountToAdd)
{
    return x => x + amountToAdd;
}

...
var adder = CreateAdder(10);
Console.WriteLine(adder(5)); // Prints 15

If this doesn't help, please clarify your question.