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<int> TryThis(MyIntReturn MyAction)
{
try
{
return MyAction();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
private static Nullable<string> TryThis(MyStringReturn MyAction)
{
try
{
return MyAction();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
}
Nullable<string>
.string
is a reference type. \$\endgroup\$ – Daniel A. White Oct 26 '12 at 17:12string
is a ref type soNullable
doesn't make any sense here. \$\endgroup\$ – JonH Oct 26 '12 at 17:13