type conversion is converting one type of data to another type. it is also known as type casting. in c#, type casting has two forms −
implicit type conversion − these conversions are performed by c# in a type-safe manner. for example, are conversions from smaller to larger integral types and conversions from derived classes to base classes.
explicit type conversion − 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 −
using system;
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 −
| sr.no. | methods & description |
|---|---|
| 1 |
toboolean converts a type to a boolean value, where possible. |
| 2 |
tobyte converts a type to a byte. |
| 3 |
tochar converts a type to a single unicode character, where possible. |
| 4 |
todatetime converts a type (integer or string type) to date-time structures. |
| 5 |
todecimal converts a floating point or integer type to a decimal type. |
| 6 |
todouble converts a type to a double type. |
| 7 |
toint16 converts a type to a 16-bit integer. |
| 8 |
toint32 converts a type to a 32-bit integer. |
| 9 |
toint64 converts a type to a 64-bit integer. |
| 10 |
tosbyte converts a type to a signed byte type. |
| 11 |
tosingle converts a type to a small floating point number. |
| 12 |
tostring converts a type to a string. |
| 13 |
totype converts a type to a specified type. |
| 14 |
touint16 converts a type to an unsigned int type. |
| 15 |
touint32 converts a type to an unsigned long type. |
| 16 |
touint64 converts a type to an unsigned big integer. |
the following example converts various value types to string type −
using system;
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