How to accept a function reference as an argument?

I am currently passing an EventHandler object to the util function, for example:

 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 this to something like this?

 Timer newTimer(int interval, ref Function handler) { .... timer.Elapsed += new System.Timers.ElapsedEventHandler(handler); .... } newTimer(1000, ref myTimer_Tick); 
+4
source share
1 answer

It is not clear why you are using ref here, but if myTimer_Tick has the correct signature, you do not need to change your method at all - you can simply use:

 newTimer(1000, myTimer_Tick); 

Instead, the method group transformation is used, rather than an explicit expression about creating a delegate. He does the same thing though.

If you want to use the parameterless void methods, you can write a helper method to accept an Action and wrap it in an ElapsedEventHandler using a lambda expression:

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

All Articles