I'm not sure what all of your use case is, but it seems like a suitable scenario for using delegates. Let's start by defining a delegate:
public delegate T Operation<T>(T arg, T step);
and now suppose you have a class with operators:
public class Foo { public static Foo operator + (Foo left, Foo right) { ... } public static Foo operator + (Foo left, Foo right) { ... } }
In a class where you want to completely process the logic, you can use similar code:
public class Bar { // The method you look for: public Foo Increment(Foo value, string @operator, Foo step) { Operation<Foo> operation = null; switch(@operator) { case "+": operation = (v, s) => v + s; break; case "-": operation = (v, s) => v - s; break; ... } if (operation != null) { return operation(value, step); } else { throw new NotSupportedException( "Operator '" + @operator "' is not supported"); } } }
Instead of the Foo class that I used for clarity, you can use any of the primitive types in .NET that support these operations ( int , double , long , etc.).
Instead of defining your own delegate (e.g. Operation<T> , you can use buil-in Func<T, T> .
I would recommend using an enumeration instead of a string for the operators ( + , - , ...), since the string will allow you to pass an invalid value.
source share