It\'s a real shame that in .Net there is no polymorphism for numbers, i.e. no INumeric interface that unifies the different kinds of numerical types such as bool, byte, uint
The csharp language team is already looking into this. If you want a view onto the future of type classes in C# start reading at
https://github.com/dotnet/csharplang/issues/164
It seems to have the support of Mads Torgesson so it's not just a random post by a wandering Haskell fanboy.
The example given of a typeclass or shape in C# land is
public shape SGroup<T>
{
static T operator +(T t1, T t2);
static T Zero { get; }
}
notice this is not like an interface. It is declaring static method that belong to SGroup. Read on for more details and discussion.
If you plan to use C# 4.0 then you can easily simulate generic mathematical operations using dynamic
. Here is an example of a simple addition function (for more information see this blog):
public static T Add<T>(T a, T b) {
dynamic ad = a;
dynamic bd = b;
return ad + bd;
}
I haven't played with this, so I can't say much about the performance. There will certainly be some performance price for using dynamic, but I think the DLR should be able to do very effective optimizations if you'll invoke the function multiple times. In fact, I won't be surprised if it had similar performance profile as Generic Operators mentioned above.
Someone has already gone to the effort of writing something which may solve your delemma. It's called Generic Operators, and is available in the Miscellaneous Utility Library.