1

I need some help declaring the Subscribe() method below. Pretty much i want to intercept anybody who wants to register to future updates and tell them about previous events.

class Test
{
    public delegate void OnCount(int nCount);
    protected event OnCount _event;

    Test()
    {
        _event += countHandler; // This subscribes ok
        _event(6);

        Subscribe(countHandler); // I would like to pass this
    }

    void countHandler(int n) { int m = n; }

    void Subscribe(**Action<int>** callback) // Not sure how to declare argument (doesn't compile)
    {
        _event += callback;      // Subscribe to future values (doesn't compile)
        callback(5);             // Pass current/previous values
    }
}
edwinc
  • 1,658
  • 1
  • 14
  • 14
  • `doesn't compile` -- That's because `_event` is expecting an object of type `OnCount`, but you're handing it an object of type `Action`. `Not sure how to declare argument` -- Declare it as an `OnCount`. That said, I'm not quite sure what you're trying to accomplish here. If you just want to know if an event has already been subscribed, see http://stackoverflow.com/questions/136975/has-an-event-handler-already-been-added or http://stackoverflow.com/questions/1129517/c-sharp-how-to-find-if-an-event-is-hooked-up – Robert Harvey Apr 25 '13 at 22:14

2 Answers2

2

You'd typically use the same delegate type as the event:

void Subscribe(OnCount callback)
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Sorry i didn't read this before i posted my answer. Your answer is what i was looking for. Thanks. – edwinc Apr 26 '13 at 12:50
0

I just figured it out:

public class Test
{
    public delegate void OnCount(int nCount);
    protected event OnCount _event;

    public Test()
    {
        Subscribe(countHandler); // Pass method to callback
    }

    void countHandler(int n) { System.Diagnostics.Debug.WriteLine("n:" + n.ToString()); }

    void Subscribe(Action<int> callback)
    {
        _event -= new OnCount(callback); // Avoid re-subscriptions
        _event += new OnCount(callback); // Subscribe to future values 
        callback(5);                     // Pass current values
    }
}
edwinc
  • 1,658
  • 1
  • 14
  • 14