Numeric Conversions - CSharp Language Basics

CSharp examples for Language Basics:Number

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:

Demo Code

using System;//w  w  w  .  j av a 2 s  . c o m
class Test
{
   static void Main(){
      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
      Console.WriteLine(z);
   }
}

Result

Floating-point to integral conversions

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

int i = 1;
float f = i;
Console.WriteLine (i);
Console.WriteLine (f);

The reverse conversion must be explicit:

int i2 = (int)f;

When you cast from a floating-point number to an integral, any fractional portion is truncated; no rounding is performed.


Related Tutorials