Generic types must be known at compile time, so you cannot create dynamic delegates. If you specify a data type, you can create a delegate dictionary:
Dictionary<string, Func<int, int, bool>> comparisons; comparisons.add("<", (x, y) => x < y); comparisons.add("==", (x, y) => x == y); comparisons.add(">", (x, y) => x > y);
You can use the IComparable interface to allow different types, but then you can only use it for the CompareTo method to implement the operators:
Dictionary<string, Func<IComparable, IComparable, bool>> comparisons; comparisons.add("<", (x, y) => x.CompareTo(y) < 0); comparisons.add("==", (x, y) => x.CompareTo(y) == 0); comparisons.add(">", (x, y) => x.CompareTo(y) > 0);
This, of course, gives less restrictions on the data used, you can, for example, pass the value of string and a DateTime operator delegate, and it compiles just fine. It is not until you run it so that it does not work.
Guffa source share