I want to use any method as a parameter of a method that cares about exception handling, something like this:
public void Run(){
string result1 = (string)HandlingMethod(GiveMeString, "Hello");
int result2 = (int)HandlingMethod(CountSomething, 1, 2);
}
public object HandlingMethod(something method, manyDifferentTypesOfParameters...){
try{
return method(manyDifferentTypesOfParameters)
}catch(Exception ex){
....
}
}
public string GiveMeString(string text){
return text + "World";
}
public int CountSomething(int n1, int n2){
return n1 + n2;
}
Is it possible to do it in C# .Net?
EDIT:
I found this solution, but I'm not sure how safe and ok it is. What do you think?
public class Program
{
public static void Main(string[] args)
{
string result1 = (string)Test(new Func<string,string>(TestPrint), "hello");
int result2 = (int)Test(new Func<int, int, int>(TestPrint2), 4, 5);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
public static object Test(Delegate method, params object[] args){
Console.WriteLine("test test");
return method.DynamicInvoke(args);
}
public static string TestPrint(string text){
return text;
}
public static int TestPrint2(int n1, int n2){
return n1 + n2 +1;
}
}