Pass a method as a parameter to another method
.net, c#, delegates, methods, winforms
Solution
For a method without parameters and returning void, you can use Action:
private void MeasureTime(Action m)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
m();
sw.Stop();
ShowTakenTime(sw.ElapsedMilliseconds);
}
If you have some parameters or a return type, use Func
Problem
I am having a method called LoadData which gets data from DataBase and fills a `DataGridView`. I am using a Stopwatch to measure how long my method takes to finish it's job as below : ``` private void btnLoadData_Click(object sender, EventArgs e) { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); LoadData (); sw.Stop(); ShowTakenTime(sw.ElapsedMilliseconds); } ``` I want something that can do The following : ``` private void MeasureTime(Method m) { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); m.Invoke(); sw.Stop(); ShowTakenTime(sw.ElapsedMilliseconds); } ``` so that I can pass the LoadData method to it and it does the rest for me. ``` MeasureTime(LoadData()); ``` How can I do that?