Type conversion is basically type casting or converting one type of data to another type. In C#, type casting has two forms:
These conversions are performed by C# in a type-safe manner. Examples are conversions from smaller to larger integral types and conversions from derived classes to base classes.
These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator..
The following example shows an explicit type conversion:
{
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:
|
S.N |
Methods & Description |
|
1 |
ToBoolean |
|
2 |
ToByte |
|
3 |
ToChar |
|
4 |
ToDateTime |
|
5 |
ToDecimal |
|
6 |
ToDouble |
|
7 |
ToInt16 |
|
8 |
ToInt32 |
|
9 |
ToInt64 |
|
10 |
ToSbyte |
|
11 |
ToSingle |
|
12 |
ToString |
|
13 |
ToType |
|
14 |
ToUInt16 |
|
15 |
ToUInt32 |
|
16 |
ToUInt64 |