Type Conversion in C# Programming

Type Conversion is process of converting one data type into another data type. This help us choose most appropriate type for the variable. It is also known as type casting.

It can be done in two ways:

  • Implicit Type Conversion
  • Explicit Type Conversion.

Implicit Type Conversion

Implicit Type Conversion is done automatically by C# compiler. It occurs when we assign lower range value to higher range variable. In this conversion, no data will be lost so it is a safe type conversion. For Example:

int a = 1;
long b = a;

Some possible implicit type conversions are listed below:

sbyte int, short, long, double, decimal, float
byte int, short, ushort, uint, ulong, long, double, decimal, float
short int, long, double, decimal, float
ushort int, uint. long, ulong. double, decimal, float
uint long, float, ulong, double, decimal
int long, double, decimal, float
long double, decimal, float
ulong double, decimal, float
float double
char int, long, double, float, decimal, uint, ulong, ushort (only where there is numeric value stored in it)

Explicit Type Conversion

Explicit Type Conversion is done by users using cast operator. This conversion might cause data loss or conversion might not be possible in some cases due to type mismatch. So, it is also known as unsafe conversion. For example:

double a = 1.1d;
long b = (long)a;

Here, after conversion 1.1 is changed to 1. So, there is data loss. 

Explicit type conversion can be done among any for following data types but some data can be lost:

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

Methods of Type Conversions

Some built-in type conversion methods are:

Method Description
ToBoolean converts a type to a boolean value
ToByte converts a type to a byte
ToChar converts a type to a single character
ToDateTime converts a integer type or string type to date-time structures
ToDecimal converts a floating point or integer type to a decimal type
ToDouble converts a type to a double type
ToInt16 converts a type to a 16-bit integer
ToInt32 converts a type to a 32-bit integer
ToInt64 converts a type to a 64-bit integer
ToSbyte converts a type to a signed byte
ToSingle converts a type to a small floating point number
ToString converts a type to a string
ToType converts a type to a specified type
ToUInt16 converts a type to an unsigned int type
ToUInt32 converts a type to an unsigned long type
ToUInt64 converts a type to an unsigned big integer