Type casting is converting one type of data to another type. The two forms are −
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 are the built-in type conversion methods −
| Sr.No | Method & 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. |
The following example convert integer to string type −
Example
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int i = 20;
Console.WriteLine(i.ToString());
Console.ReadKey();
}
}
}Output
20