Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C#

Learn step by step



Type Conversion

Type conversion (or typecasting) is the technique to change an entity from one data type into another. In general there are two types of type conversion.

  • Implicit conversion
  • Explicit conversion

Implicit conversion

Implicit conversion (or coercion) is automatic type conversion by the compiler. In C# it does not require a special syntax because the type conversion is safe and no data will be lost. In the following example the value of an integer is stored in a long. This is safe because an integer is 4 bytes (on a 32 bit computer), and a long is 8 bytes. So every value that fits in an integer fits in a long.

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

ushort

int , uint, long, ulong, float, double, or decimal
int long , float, double, or decimal
uint long , ulong, float, double, or decimal
long float , double, or decimal
char ushort , int, uint, long, ulong, float, double, or decimal
float double

ulong

float , double, or decimal


int i = 12345678;
long l = i;
//It is also possible to cast a derived class to a base class without using a special syntax.
Explicit conversion

Instead of implicit conversion explicit conversion (or casting) is not done by the compiler. It is explicitly defined in the application (i.e. it requires a cast operator). There is a possible risk of losing data when the source and destination have a different size or when the source is converted to a base class.
This example will not compile without the explicit cast operator since a double fits not in an integer. Also the value will lose its precision since an integer does not store decimal values.

From

To

sbyte byte , ushort, uint, ulong, or char
byte Sbyte or char
short sbyte , byte, ushort, uint, ulong, or char
ushort sbyte , byte, short, or char
int sbyte , byte, short, ushort, uint, ulong, or char
uint sbyte , byte, short, ushort, int, or char
long sbyte , byte, short, ushort, int, uint, ulong, or char
ulong sbyte , byte, short, ushort, int, uint, long, or char
char sbyte , byte, or short
float sbyte , byte, short, ushort, int, uint, long, ulong, char, or decimal
double sbyte , byte, short, ushort, int, uint, long, ulong, char, float, or decimal
decimal sbyte , byte, short, ushort, int, uint, long, ulong, char, float, or double


double d = 10.345;
int i = (int)d;


Related Videos