Say I want to have a method that takes any kind of number, is there a base class (or some other concept) that I can use?
As far as I know I have to make overloads for all the different numeric types (Int32
, Int16
, Byte
, UInt32
, Double
, Float
, Decimal
, etc). This seems awfully tedious. Either that or use the type object
and throw exceptions if they are not convertible or assignable to a double
- which is pretty bad as it means no compile time checking.
UPDATE:
OK thanks for the comments, you are right Scarecrow and Marc, in fact declaring it as Double
actually works for all except Decimal
.
So the answer I was looking for is Double
- it acts like a base class here since most numeric types are assignable to it. (I guess Decimal
is not assignable to Double
, as it could get too big.)
public void TestFormatDollars() {
int i = 5;
string str = FormatDollars(i); // this is OK
byte b = 5;
str = FormatDollars(b); // this is OK
decimal d = 5;
str = FormatDollars(d); // this does not compile - decimal is not assignable to double
}
public static string FormatDollars(double num) {
return "$" + num;
}