- Implicit Type Conversion : In This type of conversion the conversion is done automatically by the compiler, from smaller data type to larger data type or from derived classes to base class
- Explicit Type Conversion: In This type of conversion the conversion is done automatically by the compiler, from smaller data type to larger data type or from derived classes to base class
1 2 3 4 | int i_num; i_num = 78; double d_num; d_num = i_num; // Implicit Conversion |
Explicit Type Conversion Example :
1 2 3 4 | int i_num; double d_num; d_num = 78.45; i_num = (int)d_num; //Explicity Type Conversion |
C# provide three difference ways for data type conversion
- Type Cast Operator ()
- Convert Class
- Paring
| Method | Description |
|---|---|
| ToBoolean | Converts a type to a Boolean value, where possible. |
| ToByte | Converts a type to a byte. |
| ToChar | Converts a type to a single Unicode character, where possible. |
| ToDecimal | Converts a floating point or integer type to a decimal type. |
| ToDouble | Converts a type to a double type. |
| ToInt32 | Converts a type to a 32-bit integer. |
| ToInt16 | Converts a type to a 16-bit integer. |
| ToInt64 | Converts a type to a 64-bit integer. |
| ToString | Converts a type to a string. |
The following example converts various value types to string type −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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
No comments:
Post a Comment