C# Type Conversion
Type conversion fundamentally involves type casting, or the process of converting data from one type to another. In C#, type casting comes in two forms:
Implicit Type Conversion - These conversions are C#'s default safe conversions that do not result in data loss. For example, converting from a smaller integer type to a larger integer type, or from a derived class to a base class.
Explicit Type Conversion - Explicit type conversion, also known as type casting, requires the use of a cast operator and can lead to data loss.
The following example demonstrates an explicit type conversion:
Example
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;
// Cast double to int
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
5673
C# Type Conversion Methods
C# provides the following built-in type conversion methods:
No. | Method & Description |
---|---|
1 | ToBoolean <br>Converts a type to a Boolean value, if possible. |
2 | ToByte <br>Converts a type to a byte type. |
3 | ToChar <br>Converts a type to a single Unicode character, if possible. |
4 | ToDateTime <br>Converts a type (integer or string) to a date-time structure. |
5 | ToDecimal <br>Converts a floating point or integer type to a decimal type. |
6 | ToDouble <br>Converts a type to a double type. |
7 | ToInt16 <br>Converts a type to a 16-bit integer type. |
8 | ToInt32 <br>Converts a type to a 32-bit integer type. |
9 | ToInt64 <br>Converts a type to a 64-bit integer type. |
10 | ToSByte <br>Converts a type to a signed byte type. |
11 | ToSingle <br>Converts a type to a small floating point number. |
12 | ToString <br>Converts a type to a string. |
13 | ToType <br>Converts a type to a specified type. |
14 | ToUInt16 <br>Converts a type to a 16-bit unsigned integer type. |
15 | ToUInt32 <br>Converts a type to a 32-bit unsigned integer type. |
16 | ToUInt64 <br>Converts a type to a 64-bit unsigned integer type. |
The following example converts various types to string types:
Example
namespace TypeConversionApplication
{
class StringConversion
{
static void Main(string[] args)
{
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
75
53.005
2345.7652
True