maxp
maxp

Reputation: 25151

Add event to another event? c#

class a 
{
    public event Action foo;
    var zzz = new b();
    foo += zzz.bar;
}

class b 
{
    public Action bar;
}

The above (pseudo) code works and compiles fine.

However, if i change bar to public event Action bar I cant then add it to foo. Basically I would like to add one event to another. Im aware this could sound abit ridiculous.

Upvotes: 3

Views: 1125

Answers (3)

digEmAll
digEmAll

Reputation: 57210

What do you want to achieve is something like this (I guess):

  1. foo event is triggered:
    call all foo subscribed event handlers plus all bar subscribed event handlers.
  2. bar is triggered:
    call all bar subscribed event handlers plus all foo subscribed event handlers.

class a 
{
    public event Action foo;
    b zzz = new b();
    public a()
    {
        // this allow you to achieve point (1)
        foo += zzz.FireBarEvent;
        // this allow you to achieve point (2)
        zzz.bar += OnBar;
    }
    void OnBar()
    {
        FireFooEvent();
    }
    void FireFooEvent()
    {
        if(foo != null)
            foo();
    }
}

class b 
{
    public event Action bar;
    public void FireBarEvent()
    {
       if(bar != null)
           bar();
    }
}

CAVEAT:

this code (if (1) and (2) options are both enabled) cause an infinite numbers of calls i.e.:

foo --> bar --> foo --> bar ...

that has to be managed properly.

Upvotes: 1

GvS
GvS

Reputation: 52518

If bar is a public event, then you use a lambda to invoke the bar event:

foo += () => zzz.bar();

This is not the exact syntax, researching...

This is not possible, because you cannot call the bar event from outside the class it is defined in.

You should use a solution like this;

class b {
    public Action bar;
    public void InvokeBar() {
       if (bar != null) bar();
    }
}

Then you can use InvokeBar as a target for your event.

Upvotes: 1

Lukáš Novotný
Lukáš Novotný

Reputation: 9052

IIRC you can't invoke events from another class directly.

class A {
    public A() {
        b = new B(this);
    }

    private B b;
    public event Action Foo;
}

class B {
    public B(A a) {
        a.Foo += InvokeBar;
    }

    public event Action Bar;

    private void InvokeBar() {
        if (Bar != null)
            Bar();
    }
}

Upvotes: 3

Related Questions