I read an answer to a question on Stack Overflow that contained the following suggested code:
Action<Exception> logAndEat = ex =>
{
// Log Error and eat it
};
try
{
// Call to a WebService
}
catch (SoapException ex)
{
logAndEat(ex);
}
catch (HttpException ex)
{
logAndEat(ex);
}
catch (WebException ex)
{
logAndEat(ex);
}
My question is: what is the advantage (if any) of using a lambda expression for LogAndEat as opposed to the (in my view simpler and more obvious) private method as follows:
private void LogAndEat(Exception ex)
{
// Log Error and eat it
}
Edit: Thanks for the answers so far but just restating my fundamental question a little more clearly: which approach is better/would you recommend in this instance? A lambda expression or a private method?
Thanks everyone for the great answers which I have up-voted, but I thought I’d summarize them to try and capture the pros and cons in one answer.
Pros of using a lambda expression (LE) instead of a private method:
Cons of using a lambda expression instead of a private method:
There is also the more subjective issue of maintainability and one could argue that LE are not as well understood by most developers as a private method and thus are somewhat less maintainable. One could also argue that a LE improves maintainability because it is encapsulated in the method in which it is called as opposed to a private method which is visible to the entire class.