Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no base type of Number in c#?

Tags:

c#

.net

Unlike in java why c# does not have a supertype of Number for Floats, Integers etc? Any reasoning behind avoiding Number in c#?

like image 363
suhair Avatar asked Sep 13 '09 17:09

suhair


3 Answers

Because value types can't be inherited.

like image 120
Felipe Pessoto Avatar answered Oct 21 '22 16:10

Felipe Pessoto


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.

like image 39
Marc Gravell Avatar answered Oct 21 '22 18:10

Marc Gravell


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.

like image 3
Dario Avatar answered Oct 21 '22 18:10

Dario