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);
It’s not clear why you’re using
refhere, but ifmyTimer_Tickhas the right signature, you don’t need to change your method at all – you can just use: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
Actionand wrap that in anElapsedEventHandlervia a lambda expression: