HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

How to simplify these delegate functions?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thesedelegatesimplifyhowfunctions

Problem

I'm looking for a way to simplify this code, because I could develop more overloads for TryThis I made the string and int both of class Nullable so that in each overloaded function, the catch block could return the same value.

The problem is I need, if possible, no overloads of TryThis. The function overloads are both identical, except for the type of delegate they are passed. Is there some kind of variable that would encompass any delegate that can be executed?

class Program
{
    delegate int MyIntReturn();
    delegate string MyStringReturn();
    static private MyIntReturn ReadInt = () => {return int.Parse(Console.ReadLine()); };
    static private MyStringReturn ReadString = () => { return Console.ReadLine(); };

    static private Nullable TryThis(MyIntReturn MyAction)
    {
        try
        {
            return MyAction();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            return null;
        }
    }
    private static Nullable TryThis(MyStringReturn MyAction)
    {
        try
        {
            return MyAction();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            return null;
        }
    }


}

Solution

You can use the generic delegate Func<>:

static private T TryThis(Func MyAction) {
    try {
        return MyAction();
    } catch (Exception ex) {
        Console.WriteLine(ex.ToString());
        return default(T);
    }
}

Code Snippets

static private T TryThis<T>(Func<T> MyAction) {
    try {
        return MyAction();
    } catch (Exception ex) {
        Console.WriteLine(ex.ToString());
        return default(T);
    }
}

Context

StackExchange Code Review Q#17968, answer score: 5

Revisions (0)

No revisions yet.