How to pass a method of reference to another method in C #

I would like to pass a method reference to another method and store it as a variable. Later I would like to use this link to define an event handler.

When creating an event handler, a method reference is passed, for example:

myButton.Click += new RoutedEventHandler(myButton_Click);

      

And if you look at the constructor for "RoutedEventHandler" from intelliSense it looks like this:

RoutedEventHandler(void(object, RoutedEventArgs))

      

What I would like to do is pass the "myButton_Click" method to another static method and then create an event handler. How do I pass a reference to a static method? I tried the following, but it doesn't compile:

public class EventBuilder
{
    private static void(object, RoutedEventArgs) _buttonClickHandler;

    public static void EventBuilder(void(object, RoutedEventArgs) buttonClickHandler)
    {
        _buttonClickHandler = buttonClickHandler;
    }

    public static void EnableClickEvent()
    {
        myButton.Click += new RoutedEventHandler(_buttonClickHandler);
    }
}

      

Thanks Ben

0


source to share


2 answers


To refer to a method reference (called delegate in .NET) use the handler name, not the signature.



public class EventBuilder
{
    private static RoutedEventHandler _buttonClickHandler;

    public EventBuilder(RoutedEventHandler buttonClickHandler)
    {
        _buttonClickHandler = buttonClickHandler;
    }

    public static void EnableClickEvent()
    {
        myButton.Click += new RoutedEventHandler(_buttonClickHandler);
    }
}

      

+5


source


try



private static delegate void(object sender, RoutedEventArgs e) _buttonClickHandler;

      

0


source







All Articles