C# Numeric Types
In this chapter you will learn:
- C# Numeric Types
- Integral?unsigned
- Real Numbers
- Note for real numbers in C#
- Example for the range of integer types
Description
C# has the predefined numeric types shown in the following table.
C# type | System type | Suffix | Size | Range |
---|---|---|---|---|
sbyte | SByte | N/A | 8 bits | -27 to 27 -1 |
short | Int16 | N/A | 16 bits | -215 to 215-1 |
int | Int32 | N/A | 32 bits | -231 to 231-1 |
long | Int64 | L | 64 bits | -263 to 263-1 |
Integral?unsigned
C# type | System type | Suffix | Size | Range |
---|---|---|---|---|
byte | Byte | N/A | 8 bits | 0 to 28 -1 |
ushort | UInt16 | N/A | 16 bits | 0 to 216-1 |
uint | UInt32 | U | 32 bits | 0 to 232-1 |
ulong | UInt64 | UL | 64 bits | 0 to 264-1 |
Real Numbers
C# type | System type | Suffix | Size | Range |
---|---|---|---|---|
float | Single | F | 32 bits | +/- (~10-45 to 1038) |
double | Double | D | 64 bits | +/- (~10-324 to 10308) |
decimal | Decimal | M | 128 bits | +/- (~10-28 to 1028) |
Note
float
and double
are called floating-point types and are
typically used for scientific calculations.
The decimal
type is typically used for
financial calculations, where base-10-accurate arithmetic and high precision are
required.
Example
The following code prints out the range of integer types in C#.
using System;// w w w . ja v a2 s .c o m
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class MainClass
{
public static void Main()
{
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(byte).ToString(), sizeof(byte), byte.MinValue, byte.MaxValue);
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(char).ToString(), sizeof(char), (int)char.MinValue, (int)char.MaxValue);
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(short).ToString(), sizeof(short), short.MinValue, short.MaxValue);
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(int).ToString(), sizeof(int), int.MinValue, int.MaxValue);
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(long).ToString(), sizeof(long), long.MinValue, long.MaxValue);
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(sbyte).ToString(), sizeof(sbyte), sbyte.MinValue, sbyte.MaxValue);
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(ushort).ToString(), sizeof(ushort), ushort.MinValue, ushort.MaxValue);
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(uint).ToString(), sizeof(uint), uint.MinValue, uint.MaxValue);
Console.WriteLine("{0}: bytes: {1}, range: [{2},{3}]",
typeof(ulong).ToString(), sizeof(ulong), ulong.MinValue, ulong.MaxValue);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: