Unlike in java why c# does not have a supertype of Number for Floats, Integers etc? Any reasoning behind avoiding Number in c#?
Because value types can't be inherited.
I don't know if true, but one explanation I heard was weight - in particular for the small frameworks (Compact Framework, Silverlight, Micro Framework); I'm not convinced by this...
Far more convincing is that by itself knowing it is a number doesn't provide much; for example, integer division works very differently to floating point, and operators aren't always as simple as you'd like (think DateTime + TimeSpan => DateTime
, DateTime - DateTime => TimeSpan
).
If it helps, MiscUtil offers generic operator support, allowing things like:
T x = ..., y = ...; // any T that has suitable operators
T sum = Operator.Add(x,y);
All very cleanly and efficiently. Note, however, that there is no compile-time validation (since there are no suitable generic constraints). But it works.
It might have performance reasons - Numbers, being struct
-types, are stack-allocated and fast but do not allow inheritance structures. Using them in an OO-way would require a very large amount of auto/unboxing and additionally big much performance reductions due to much more memory consumption and vtable lookups to solve the polymorphism.
Java has introduced object-oriented wrappers and ends up with different and incompatible implementations for one and the same thing with is even more strange.
A better possibility for providing fast abstractions for numbers would be the introduction of typeclasses/concepts like in Haskell or C++ where you could write:
sum :: (Num t) => [t] -> t
read as Sum takes a list of elements of type t
- where t is a number type - and returns such a number. This mechanism could be optimized away at compile-time without any performance overhead. But neither .NET nor Java have such techniques.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With