Today I finally \"got\" the Func<> delegate and saw how I could use it to make some of my less readable LINQ queries (hopefully) more readable.
Here\'s a simpl
I am using the Func and Action delegates for a common handling of exceptions. I often find myself building the same try-catch block over and over again, because I keep them as short as possible. Delegate and Action can reduces the try-catch code duplication.
A really simple example would be:
...
DoSomethingPotentiallyBad((x) => x * 2, 0); // both delegates do
DoSomethingPotentiallyBad((x) => 2 / x, 0); // something different ...
...
static int DoSomethingPotentiallyBad(Func function, int input)
{
// ... but get exception handled all the same way
try
{
return function.Invoke(input);
}
catch
{
Console.WriteLine("Evaluation failed! Return 0.");
return 0;
}
}
This example is very artificial and doesn't show the power of it. But supposed that you have something like database operations instead and you want to retry each failing database operation 5 times (which involves using flags, a finally-block and a while loop) and want the same application-wide logging, then you have just one place to put that try-catch block: It's the method, which takes a Func or Action delegate as argument. Code which handles business logic is almost free of those try-catch-blocks and thus are more readable.
For some more advance example and longer description have a look at: Action Policy