Is there a generic numeric type in C#?

Even if there were a base type or interface that encompasses numeric types, because you've wrapped the constraint in a Func it wouldn't do you any good. the input types for Func are contravariant, so its parameters can't me more derived than what's declared.

In other words, you can't replace a Func<DateTime, ValueType, DateTime> with a Func<DateTime, int, DateTime> like you can with IEnumerable<T> (you can replace an IEnumerable<ValueType> with an IEnumerable<int>)

I think your best bets are dynamic (still type safe, but at run-time versus compile-time) or double or decimal if you want to do math and don't have to stay in the same type.


No, there is not. Generics and arithmetic operations (+, -, *, /, etc.) simply do not work together. This is an issue that is brought up many times and the C# design comitee has never addressed (to be fair, this feature would need work on the CLR too, as pointed out by Eric Lippert in answer linked further on).

Curisously, if you inspect the source code of the .NET Framework you'll see that in some stage of development there was an IArithmetic<T> interface, but it was scrapped; see here.

You can read more about it, in this SO answer.

Tags:

C#

.Net