Consider a situation where I have three (or more) ways of performing a calculation, each of which can fail with an exception. In order to attempt each calculation until we f
Given that the calculation methods have the same parameterless signature, you can register them in a list, and iterate through that list and execute the methods. Probably it would be even better for you to use Func meaning "a function that returns a result of type double".
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class CalculationException : Exception { }
class Program
{
static double Calc1() { throw new CalculationException(); }
static double Calc2() { throw new CalculationException(); }
static double Calc3() { return 42.0; }
static void Main(string[] args)
{
var methods = new List> {
new Func(Calc1),
new Func(Calc2),
new Func(Calc3)
};
double? result = null;
foreach (var method in methods)
{
try {
result = method();
break;
}
catch (CalculationException ex) {
// handle exception
}
}
Console.WriteLine(result.Value);
}
}