JarbingleMan
JarbingleMan

Reputation: 460

Pass method as a parameter and have it subscribe to an event inside the function?

I am Class B, and I want to subscribe to an event within A using my method Foo(). However, I would like A to manage the subscription. My thought was to send my method to A and have A subscribe it there, but I am unable to find a pattern of how to do this online. Is what I want even possible?

Please note I am aware in my example below I could subscribe to A's events directly using:

this._A.MyEvent += (s, e) => this.MyFunction(); 

but this is not what I am wanting to do. Please don't offer this suggestion as I am aware this is possible.

(Envisioned pattern.)

public class A
{
    public event EventHandler MyEvent;

    public void SubscribeToEvent(Func function)
    {
        this.MyEvent += (s, e) => function;
    }

    public void UnsubscribeToEvent(Func function)
    {
        this.MyEvent -= (s, e) => function;
    }
}

public class B
{
    public A _A;

    public B()
    {
        this._A = new A();
    }

    public void MyFunction(object sender, EventArgs e)
    {
        // Do things
    }

    public void Subscribe()
    {
        this._A.SubscribeToEvent(this.MyFunction);
    }

    public void Unsubscribe()
    {
        this._A.UnsubscribeEvent(this.MyFunction);
    }
}

Upvotes: 0

Views: 1082

Answers (1)

Kit
Kit

Reputation: 21709

With a change of your method signatures in class A your proposed pattern will work.

public class A
{
    public event EventHandler MyEvent;

    public void SubscribeToEvent(EventHandler function)
    {
        this.MyEvent += function;
    }

    public void UnsubscribeToEvent(EventHandler function)
    {
        this.MyEvent -= function;
    }
}

Upvotes: 3

Related Questions