Delegate – Functional Methods – Func / Action with .NET 4.5

Delegates in .NET allow one to pass functions as parameter and call it.  One common example is callback functions.

Note: Func is the same as Action, but Func can have a return value of any type.  Action returns void.

Here is one common scenario.  I want to do X, but I want have a big try/catch to handle the any possible exception and retry X up to n times.

I can use Action, a built-in .NET delegate to do this.

private void TryRun(Action action)
{
const int MAXTRY = 3;

int attempt = 0;
do
{
try
{
action();

break; // success
}
catch (Exception ex)
{
// process exception
Print(string.Format("Error #[{0}]: [{1}]", attempt, ex.Message));
attempt++; // increment attempt count
continue; // retry
}
} while (attempt < MAXTRY);
}

 

The use Action of lambda expressions make the code more concise.  There is no need for a separate line of code for delegate.  There is no need to define extra methods, just to be called.

private void Method1()
{
TryRun(() =>
{
// do something 1
});
}

private void Method2()
{
TryRun(() =>
{
// do something 2
});
}

Reference:

http://www.codeproject.com/Articles/117611/Delegates-in-C-Attempt-to-look-inside-Part-4

http://blackrabbitcoder.net/archive/2011/11/03/c.net-little-wonders-the-generic-action-delegates.aspx