Type conversion is fundamentally type casting, or the conversion of data from one type to another. In C#, there are two forms of type casting:
-
Implicit type conversions-these conversions are the default conversions of C# in a secure manner and do not result in data loss. For example, convert from a small integer type to a large integer type, and from a derived class to a base class.
-
Explicit type conversions-explicit type conversions, conversion requires a cast operator, and a cast can result in data loss.
The following example shows an explicit type conversion:
1.6.1. 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 results:
5673
C# type conversion method #
C# provides the following built-in type conversion methods:
| Serial number | Method & description |
|---|---|
| 1 | ToBoolean converts the type to a Boolean if possible. |
| 2 | ToByte converts types to byte types. |
| 3 | ToChar converts the type to a single Unicode character type if possible. |
| 4 | ToDateTime converts types (integer or string types) to date-time structures. |
| 5 | ToDecimal converts floating-point or integer types to decimal types. |
| 6 | ToDouble converts types to double-precision floating-point types. |
| 7 | ToInt16 converts a type to a 16-bit integer type. |
| 8 | ToInt32 converts a type to a 32-bit integer type. |
| 9 | ToInt64 converts types to 64-bit integer types. |
| 10 | ToSbyte converts types to signed byte types. |
| 11 | ToSingle converts a type to a small floating point type. |
| 12 | ToString converts a type to a string type. |
| 13 | ToType converts the type to the specified type. |
| 14 | ToUInt16 converts a type to a 16-bit unsigned integer type. |
| 15 | ToUInt32 converts a type to a 32-bit unsigned integer type. |
| 16 | ToUInt64 converts a type to a 64-bit unsigned integer type. |
The following example converts types of different values 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 results:
75
53.005
2345.7652
True