22 October 2014

Generic Method for wrapping around any code

Hey all,,
We often need to run something before some code logic and after it was executed.

As a simple example we can take the try-catch block, everybody has this in their application and is using it more then two times for sure.

What we can do in this case is to write a generic method that will allow to run our code inside a try-catch statement. This method will look like this:


Code:
public static void TryDo(Action action, ILogger logger, string messageDescription)
{
    try
    {
        action();
    }
    catch (Exception)
    {
        // Do some logging stuff here
    }
}



To use it you need something like:
Code:
TryDo(() =>
{
    var i = 1 + 2;

    Console.WriteLine("ExtremeDev Best Practice");

    // and other Logic inised
});

And if you want to return something from the executed code then you need to pass a Func instead of Action:
Code:
public static T TryDo<T>(Func<T> func)
{
    T result;
    try
    {
        result = func();
    }
    catch (Exception)
    {
        // Do some logging stuff
        throw;
    }
    return result;
}

Here is the usage of the function:
Code:
var result = TryDo(() =>
                        {
                            var i = 1 + 2;

                            Console.WriteLine("ExtremeDev Best Practice");

                            // and other Logic inised

                            return i;
                        });
Good Luck.

No comments:

Post a Comment

your thoughts are welcome:

Need more? Leave comments and subscribe to my blog.

.