I need to create a delegate type with a ref
parameter at runtime.
If I knew the parameter type(s) at compile time, I could use an explicit delegate type declaration, for example:
// S is some struct / value type, e.g. int or Guid
delegate void VoidDelSRef (ref S s);
Type td = typeof (VoidDelSRef);
That type td
is used to create a C#4 expression tree, which is compiled into a delegate.
Since the code in my expression tree modifies the parameter s
, I need to pass s
by reference.
I have to support any type S
, so I can't use an explicit delegate type declaration, because I only have Type ts = typeof (S)
and its ref
type Type tsr = ts.MakeByRefType ()
.
I tried to use Expression.GetActionType (tsr)
, but it does not allow ref
types.
How do I build a delegate with ref
parameters at runtime ?
In .NET 4, you can use the
Expression.GetDelegateType
method. UnlikeGetActionType
, it works fine withByRef
types.E.g.:
If you are on .NET 3.5, this method is not available. I recommend taking a look at its implementation (with a decompiler) if you want to replicate its functionality. It doesn't have too many dependencies; it's definitely doable.