Search code examples
c#.net.net-4.0anonymous-methods

Getting target of Action


I have created the fallowing Sample-Code:

class Program {
    static void Main(string[] args) {
        var x = new ActionTestClass();
        x.ActionTest();
        var y = x.Act.Target;
    }
}

public class ActionTestClass {
    public Action Act;
    public void ActionTest() {
        this.Act = new Action(this.ActionMethod);
    }

    private void ActionMethod() {
        MessageBox.Show("This is a test.");
    }
}

When I do this on this way, y will an object of type ActionTestClass (which is created for x). Now, when I change the line

this.Act = new Action(this.ActionMethod);

to

this.Act = new Action(() => MessageBox.Show("This is a test."));

y (the Target of the Action) will be null. Is there a way, that I can get the Target (in the sample the ActionTestClass-object) also on the way I use an Anonymous Action?


Solution

  • The lack of Target (iow == null) implies the delegate is either calling a static method or no environment has been captured (iow not a closure, just a 'function pointer').