C# Number Types

By Steve Fischer

The most commonly used number type in C# is int, which is an alias that maps to System.Int32 in the .Net development platform.

The int type is for whole numbers, including negative numbers.

What's more, the int type is a ValueType, and like other ValueTypes it inherits from the Object type.

This means the int type also has members, such as methods.

Below is an example using two methods found on the int type, MinValue and MaxValue.

C# 10 introduced top-level statements, so there is no need to declare a class with a Main method.

Console.WriteLine($"The int type ranges from {int.MinValue:N0} to {int.MaxValue:N0}");
// The int type ranges from -2,147,483,648 to 2,147,483,647

What about prices?

The go-to type for prices is the decimal type.

The decimal type is stored as a whole number, which keeps track of where the decimal is. This allows you to use the equality operator for decimal types, which is not the case for double or float.

For example:

decimal a = 0.3M;
decimal b = 0.2M;

Console.WriteLine($"Does a + b = 0.5? {a + b == 0.5M ? "Yes" : "No"}");
// Does a + b == 0.5? Yes
double c = 0.3D;
double d = 0.2D;
Console.WriteLine($"Does c + d = 0.5? {c + d == 0.5D ? "Yes" : "No"}");
// Does c + d == 0.5? No

The double type is great for storing numbers that don't have to use the equality operator, but can use greater than or less than.

If you want to let C# infer the type, you can use the var variable declaration and include a suffix on your literal.

Here is an example

var a = 3.14M;
// This is a decimal type because m and M
// are literal suffixes that denote decimal
var b = 1.75D
// This is a double type