Thanks for all the answers. Here's my solution so far. It is simpler to code than the accepted solution recommended by AspDotNetDev, and I think would be faster. Can anyone advise me further or is what I have as good as it will get?
I have a generic class defined as follows:
public class ParallelNumber<T>
private T GENERIC_TWO;
private Func<T,T,T> DIVIDE = null;
if (typeof(T) == typeof(BigInteger))
GENERIC_TWO = (T)Convert.ChangeType((BigInteger)2, typeof(T));
GENERIC_TWO = (T)Convert.ChangeType(2, typeof(T));
private void CreateDivideFunction()
ParameterExpression paramA = Expression.Parameter(typeof(T), "a"), paramB = Expression.Parameter(typeof(T), "b");
BinaryExpression body = Expression.Divide(paramA, paramB);
DIVIDE = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
public T DivideByTwo(T number)
T result = DIVIDE(number, GENERIC_TWO);
The last function DivideByTwo is the one which can now be called with any numeric type.
Would anyone else endorse this method and if so would they suggest improvements or would anyone go down a completely different root.
This method takes about 100 times longer to run than one written using (say) uint instead of generics. Can I hope to match performance using generics instead on (say) uint.
It would be ideal if at runtime, after having used the above function as follows:
ParallelNumber<uint> parallelNumber = new ParallelNumber<uint>();
uint d = parallelNumber.DivideByTwo(50);
it ran as fast as calling the function written with uint instead of generics. But then of course it ran slower when called as:
ParallelNumber<BigInteger> parallelNumber = new ParallelNumber<BigInteger>();
BigInteger d = parallelNumber.DivideByTwo(50);
Thanks for any help,