English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Type conversion is fundamentally type casting, or converting data from one type to another. In C#, type casting has two forms:
Implicit Type Conversion - These conversions are C# default conversions performed safely, which do not cause 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 casting. Explicit conversion requires the casting operator, and casting can result in data loss.
The following example shows an explicit type conversion:
namespace TypeConversionApplication { class ExplicitConversion { static void Main(string[] args) { double d = 5673.74; int i; // Explicitly convert double to int i = (int)d; Console.WriteLine(i); Console.ReadKey(); } } }
When the above code is compiled and executed, it will produce the following result:
5673
C# provides the following built-in type conversion methods:
Number | Method & Description |
---|---|
1 | ToBoolean Convert the type to a boolean type if possible. |
2 | ToByte Convert the type to a byte type. |
3 | ToChar Convert the type to a single Unicode character type if possible. |
4 | ToDateTime Convert the type (integer or string type) to a date-time structure. |
5 | ToDecimal Convert floating-point or integer types to decimal types. |
6 | ToDouble Convert the type to a double-precision floating-point type. |
7 | ToInt16 Convert the type to 16 integer type. |
8 | ToInt32 Convert the type to 32 integer type. |
9 | ToInt64 Convert the type to 64 integer type. |
10 | ToSbyte Convert the type to a signed byte type. |
11 | ToSingle Convert the type to a single-precision floating-point type. |
12 | ToString Convert the type to a string type. |
13 | ToType Convert the type to a specified type. |
14 | ToUInt16 Convert the type to 16 unsigned integer type. |
15 | ToUInt32 Convert the type to 32 unsigned integer type. |
16 | ToUInt64 Convert the type to 64 unsigned integer type. |
The following example demonstrates how to convert different value types to string types:
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 will produce the following result:
75 53.005 2345.7652 True