Search code examples
c#.netfunctionbyref

How to accept a function reference as an argument?


I'm currently passing a EventHandler object to a util function like this:

Timer newTimer(int interval, System.Timers.ElapsedEventHandler handler) {
    ....
    timer.Elapsed += handler;
    ....
}

newTimer(1000, new System.Timers.ElapsedEventHandler(myTimer_Tick));

But this is ugly and forces every caller to create an EventHandler object. How do I change that to something like this?

Timer newTimer(int interval, ref Function handler) {
    ....
    timer.Elapsed += new System.Timers.ElapsedEventHandler(handler);
    ....
}

newTimer(1000, ref myTimer_Tick);

Solution

  • It's not clear why you're using ref here, but if myTimer_Tick has the right signature, you don't need to change your method at all - you can just use:

    newTimer(1000, myTimer_Tick);
    

    This uses a method group conversion instead an explicit delegate creation statement. It does the same thing though.

    If you want to be able to use parameterless void methods, you could write a helper method to take an Action and wrap that in an ElapsedEventHandler via a lambda expression:

    Timer StartTimer(int interval, Action action)
    {
        ...
        timer.Elapsed = (sender, args) => action();
        ...
    }