Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "base class" for C# numeric value types?

Tags:

c#

types

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 convertable 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; } 
like image 369
mike nelson Avatar asked May 06 '09 09:05

mike nelson


People also ask

What is the base class for all C# classes?

Object is the base class for all data types in C#. The Object Type is the ultimate base class for all data types in C# Common Type System (CTS).

What are base and derived classes?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class.

Which class is used to define base class in C#?

The class whose members are inherited is called the base class. The class that inherits the members of the base class is called the derived class. C# and . NET support single inheritance only.

What is base class known as?

A base class is also called parent class or superclass. Derived Class: A class that is created from an existing class. The derived class inherits all members and member functions of a base class.


1 Answers

The answer is: you don't need to provide overloads for ALL the numeric types, just for Double and Decimal. All others (except maybe some very unusually large ones) will be automatically converted to these.

Not a base class but in fact that was the red herring. The base class System.ValueType doesn't help much as it includes types that are not numerics. The language reference i was reading was what got me confused in the first place :)

(I was just looking for who to attribute the answer to and it was a combination of Scarecrow and Marc Gravell, but since they were comments i have put the answer here)

like image 52
mike nelson Avatar answered Oct 02 '22 20:10

mike nelson