Storing a method as a member variable of a class

Xenoprimate picture Xenoprimate · Jan 5, 2010 · Viewed 11k times · Source

I have this as one of my members of the class 'KeyEvent':

private delegate void eventmethod();

And the constructor:

public KeyEvent(eventmethod D) 
{
    D();
}

What I want to do is instead of calling D() there, I want to store that method (D) as a member variable of KeyEvent, so something like:

stored_method = D();

And then later in another method of KeyEvent, do something like:

stored_method();

How can I do this?

Answer

Eilon picture Eilon · Jan 5, 2010

You pretty much have the code already. Just create a member field of the right delegate type and save the parameter to it just like you would with any other data type.

private eventmethod MySavedEvent;

public void KeyEvent(eventmethod D) {
    // Save the delegate
    MySavedEvent = D;
}

public void CallSavedEvent() {
    if (MySavedEvent != null) {
        MySavedEvent();
    }
}