C# Numeric Conversions

Integral to integral conversions

Integral conversions are implicit when the destination type can represent every possible value of the source type.

Otherwise, an explicit conversion is required. For example:


int x = 12345;       // int is a 32-bit integral
long y = x;          // Implicit conversion to 64-bit integral
short z = (short)x;  // Explicit conversion to 16-bit integral

Floating-point to floating-point conversions

A float can be implicitly converted to a double, since a double can represent every possible value of a float. The reverse conversion must be explicit.


float f = 0.2F;
double d = f;

f = (float)d;

Floating-point to integral conversions

All integral types may be implicitly converted to all floating-point numbers:


int i = 1;
float f = i;

The reverse conversion must be explicit:


int i2 = (int)f;

Decimal conversions

All integral types can be implicitly converted to the decimal type, since a decimal can represent every possible C# integral value. All other numeric conversions to and from a decimal type must be explicit.


int i = 1;
decimal d = i;

i = (decimal)d;




















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var