Reputation: 3607
I have the following code:
Type1 Method1(Type2 p)
{
try
{
return DoSomething(p)
}
catch{ExceptionType1}
{
}
catch{ExceptionType2}
{
}
catch{ExceptionType3}
{
}
}
Type3 Method2(Type4 p)
{
try
{
return DoSomethingElse(p)
}
catch{ExceptionType1}
{
}
catch{ExceptionType2}
{
}
catch{ExceptionType3}
{
}
}
How can i refactor this code to have something like:
TResult ExceptionalMethod(Methodx(T)){
try
{
return Methodx(T);
}
catch{ExceptionType1}
{
}
catch{ExceptionType2}
{
}
catch{ExceptionType3}
{
}
}
Thank you, Adrya
Upvotes: 0
Views: 184
Reputation: 39329
This would work:
TResult ExceptionalMethod<T, TResult>(Func<T, TResult> methodx, T parameter){
try
{
return methodx(parameter);
}
catch(ExceptionType1)
{
}
catch(ExceptionType2)
{
}
catch(ExceptionType3)
{
}
return default(TResult);
}
I do hope you do something useful in those catches.
EDIT
If you don't have the Func<T, TResult>
delegate in your version of the framework, you can easily add it, nothing special to it:
public delegate TResult Func<T, TResult>(T arg);
Upvotes: 1
Reputation: 635
This is a full sample to do what you want using delegates and Func:
using System;
namespace GenericsDelegates
{
class Program
{
static void Main(string[] args)
{
string test1 = ExceptionalMethod(TestMethod1, "test");
string test2 = ExceptionalMethod(TestMethod2, "test");
Console.WriteLine(test1);
Console.WriteLine(test2);
}
public static TResult ExceptionalMethod<T, TResult>(Func<T, TResult> func, T param)
{
return func(param);
}
public static string TestMethod1(string param)
{
return "TestMethod1-" + param;
}
public static string TestMethod2(string param)
{
return "TestMethod2-" + param;
}
}
}
Upvotes: 0
Reputation: 1502166
Sounds like you just want:
TResult ExceptionalMethod<TSource, TResult>(Func<TSource, TResult> func,
TSource input)
{
try
{
return func(input);
}
catch(ExceptionType1) {}
catch(ExceptionType2) {}
catch(ExceptionType3) {}
return default(TResult);
}
However, you should also reconsider catching exceptions and swallowing them like this - does your real code do something useful with them, such as logging?
Note the return statement at the end - that may well be inappropriate, but if you're catching those exceptions, you'll have to return something.
Upvotes: 0