I've noticed that the Delegate class has a Target property, that (presumably) returns the instance the delegate method will execute on. I want to do something like this:
void PossiblyExecuteDelegate(Action<int> method)
{
if (method.Target == null)
{
// delegate instance target is null
// do something
}
else
{
method(10);
// do something else
}
}
When calling it, I want to do something like:
class A
{
void Method(int a) {}
static void Main(string[] args)
{
A a = null;
Action<int> action = a.Method;
PossiblyExecuteDelegate(action);
}
}
But I get an ArgumentException (Delegate to an instance method cannot have a null 'this') when I try to construct the delegate. Is what I want to do possible, and how can I do it?
Ahah! found it!
You can create an open instance delegate using a CreateDelegate overload, using a delegate with the implicit 'this' first argument explicitly specified:
In order to do this you would have to pass a
static
method toPossiblyExecuteDelegate()
. This will give you anull
Target
.Edit: It is possible to pass a delegate to an instance method with no target via reflection, but not using standard compiled code.
It is possible with Delegate.CreateDelegate, exactly with the overload with the signature:
CreateDelegate (Type, object, MethodInfo)
If you specify "null" for the second parameter (target) then you have to put an extra parameter into the delegate type, that specifies the instance type, and when you invoke the delegate, the instance has to be passed as first argument, followed by the "real" parameters of the method.