We have a requirement where we need to generate delegate types on the fly. We need to generate delegates given the input parameters and the output. Both input and output would be simple types.
eg, we need to generate
int Del(int, int, int, string)
and
int Del2(int, int, string, int)
Any pointers on how to get started on this would be very helpful.
We need to parse formulate which are represented as xml.
For example, we represent (a + b) as
<ADD>
<param type="decimal">A</parameter>
<param type="decimal">B</parameter>
</ADD>
We now want this to be exposed as Func<decimal, decimal, decimal>
. We of course want to allow nested nodes in the xml, e.g:
(a + b) + (a - b * (c - d)))
We want to do this using expression trees and Expression.Compile
.
Suggestions on the feasibility of this approach are welcome.
Jon's answer works fine if you're running framework 3.5 (but not everyone is).
The 2.0 answer is to use Delegate.CreateDelegate(...)
http://msdn.microsoft.com/en-us/library/system.delegate.createdelegate.aspx
A comparison of various ways to do this including Jon's Func, Delegate.CreateDelegate, DynamicMethods and various other tricks was discussed on an earlier thread:
Delegate.CreateDelegate vs DynamicMethod vs Expression
-Oisin
The simplest way would be to use the existing
Func
family of delegates.Use
typeof(Func<,,,,>).MakeGenericType(...)
. For example, for yourint Del2(int, int, string, int)
type:If you really, really need to create a genuinely new type, perhaps you could give some more context to help us help you better.
EDIT: As Olsin says, the
Func
types are part of .NET 3.5 - but if you want to use them in .NET 2.0, you just have to declare them yourself, like this:If 4 arguments isn't enough for you, you can add more of course.