Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a delegate to an instance method with a null target?

Tags:

c#

.net

delegates

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?

like image 803
thecoop Avatar asked Jun 04 '09 16:06

thecoop


People also ask

Can delegate be null?

In short after creating an immutable copy of an event delegate and checking it for null, it is completely safe to execute the copy.

Can a delegate point to more than 1 method?

A delegate is a type safe and object oriented object that can point to another method or multiple methods which can then be invoked later. It is a reference type variable that refers to methods.

How do you instantiate a delegate?

Use the new keyword to instantiate a delegate. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method.

What is delegate target?

Definition and Usage delegateTarget property returns the element where the currently-called jQuery event handler was attached. This property is useful for delegated events attached by the on() method, where the event handler is attached at an ancestor of the element being processed.


1 Answers

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:

delegate void OpenInstanceDelegate(A instance, int a);

class A
{
    public void Method(int a) {}

    static void Main(string[] args)
    {
        A a = null;
        MethodInfo method = typeof(A).GetMethod("Method");
        OpenInstanceDelegate action = (OpenInstanceDelegate)Delegate.CreateDelegate(typeof(OpenInstanceDelegate), a, method);

        PossiblyExecuteDelegate(action);
    }
}
like image 179
thecoop Avatar answered Sep 28 '22 05:09

thecoop