Can you use .NET 4.0? If so, then it is very simple to use dynamic typing:
private object Combine(dynamic o, dynamic o1) {
Another alternative is to have a delegate card for each pair of possible types. Unfortunately, before .NET 4.0 there is no Tuple type, so you will need to define your own TypePair type as the map key. Of course, then you need to make sure that you cover all possible pairs ... but at least the compiler can help when you have the appropriate AddDelegate method:
private void AddDelegate<T1, T2>(Func<T1, T2, object> sumFunction) { // Put the function in the map ... } AddDelegate<int,int>((x, y) => x + y); AddDelegate<int,float>((x, y) => x + y); AddDelegate<int,string>((x, y) => x + y); AddDelegate<float,int>((x, y) => x + y); AddDelegate<float,float>((x, y) => x + y); AddDelegate<float,string>((x, y) => x + y); ...
Btw, I took bool from this, since the βaddingβ between bool and a float (for example) makes no sense. You can decide how you want to combine them.
As Mitch says, I would redefine your design decisions - are you sure you really need it? This is a rather strange requirement. Can you tell us something about the bigger picture? We can offer alternative approaches.
source share