How do i refactor this code by using Action<t> or Func<t> delegates

Posted by user330612 on Stack Overflow See other posts from Stack Overflow or by user330612
Published on 2010-05-02T00:20:05Z Indexed on 2010/05/02 0:27 UTC
Read the original article Hit count: 353

Filed under:
|
|
|
|

I have a sample program, which needs to execute 3 methods in a particular order. And after executing each method, should do error handling. Now i did this in a normal fashion, w/o using delegates like this.

class Program { public static void Main() {

        MyTest();
    }

    private static bool MyTest()
    {

        bool result = true;
        int m = 2;
        int temp = 0;

        try
        {
            temp = Function1(m);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for function1" + e.Message);
            result = false;
        }

        try
        {
            Function2(temp);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for function2" + e.Message);
            result = false;
        }

        try
        {
            Function3(temp);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for function3" + e.Message);
            result = false;
        }

        return result;
    }

    public static int Function1(int x)
    {
        Console.WriteLine("Sum is calculated");
        return x + x;
    }

    public static int Function2(int x)
    {
        Console.WriteLine("Difference is calculated ");
        return (x - x);
    }

    public static int Function3(int x)
    {
        return x * x;
    }
}

As you can see, this code looks ugly w/ so many try catch loops, which are all doing the same thing...so i decided that i can use delegates to refactor this code so that Try Catch can be all shoved into one method so that it looks neat. I was looking at some examples online and couldnt figure our if i shud use Action or Func delegates for this. Both look similar but im unable to get a clear idea how to implement this. Any help is gr8ly appreciated. I'm using .NET 4.0, so im allowed to use anonymous methods n lambda expressions also for this

Thanks

© Stack Overflow or respective owner

Related posts about .NET

Related posts about 3.5