Built-in numeric conversions - C# reference (original) (raw)

C# provides a set of integral and floating-point numeric types. There exists a conversion between any two numeric types, either implicit or explicit. You must use a cast expression to perform an explicit conversion.

Implicit numeric conversions

The following table shows the predefined implicit conversions between the built-in numeric types:

From To
sbyte short, int, long, float, double, decimal, or nint
byte short, ushort, int, uint, long, ulong, float, double, decimal, nint, or nuint
short int, long, float, double, or decimal, or nint
ushort int, uint, long, ulong, float, double, or decimal, nint, or nuint
int long, float, double, or decimal, nint
uint long, ulong, float, double, or decimal, or nuint
long float, double, or decimal
ulong float, double, or decimal
float double
nint long, float, double, or decimal
nuint ulong, float, double, or decimal

Note

The implicit conversions from int, uint, long, ulong, nint, or nuint to float and from long, ulong, nint, or nuint to double may cause a loss of precision, but never a loss of an order of magnitude. The other implicit numeric conversions never lose any information.

Also note that

byte a = 13;  
byte b = 300;  // CS0031: Constant value '300' cannot be converted to a 'byte'  

As the preceding example shows, if the constant value is not within the range of the destination type, a compiler error CS0031 occurs.

Explicit numeric conversions

The following table shows the predefined explicit conversions between the built-in numeric types for which there is no implicit conversion:

From To
sbyte byte, ushort, uint, ulong, or nuint
byte sbyte
short sbyte, byte, ushort, uint, ulong, or nuint
ushort sbyte, byte, or short
int sbyte, byte, short, ushort, uint, ulong, or nuint
uint sbyte, byte, short, ushort, int, or nint
long sbyte, byte, short, ushort, int, uint, ulong, nint, or nuint
ulong sbyte, byte, short, ushort, int, uint, long, nint, or nuint
float sbyte, byte, short, ushort, int, uint, long, ulong, decimal, nint, or nuint
double sbyte, byte, short, ushort, int, uint, long, ulong, float, decimal, nint, or nuint
decimal sbyte, byte, short, ushort, int, uint, long, ulong, float, double, nint, or nuint
nint sbyte, byte, short, ushort, int, uint, ulong, or nuint
nuint sbyte, byte, short, ushort, int, uint, long, or nint

Note

An explicit numeric conversion might result in data loss or throw an exception, typically an OverflowException.

Also note that:

C# language specification

For more information, see the following sections of the C# language specification:

See also