C# – Type Conversion
Jenis konversi mengubah satu jenis data ke jenis lain. Ia juga dikenal sebagai Type Casting. Di C#, tipe casting memiliki dua bentuk :
- Implicit type conversion – Konversi ini dilakukan oleh C # dengan cara yang aman. Misalnya, adalah konversi dari tipe integral yang lebih kecil ke yang lebih besar dan konversi dari kelas turunan ke kelas dasar.
- Explicit type conversion – Konversi ini dilakukan secara eksplisit oleh pengguna menggunakan fungsi yang telah ditentukan sebelumnya. Konversi eksplisit membutuhkan operator cast.
Contoh berikut menunjukkan jenis konversi eksplisit :
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();
}
}
}Ketika kode di atas dikompilasi dan dijalankan, itu menghasilkan hasil sebagai berikut :
5673C# Type Conversion Methods
C # menyediakan metode konversi tipe built-in berikut :
| Sr.No. | Methods & Description |
|---|---|
| 1 | ToBoolean Converts a type to a Boolean value, where possible. |
| 2 | ToByteConverts a type to a byte. |
| 3 | ToCharConverts a type to a single Unicode character, where possible. |
| 4 | ToDateTimeConverts a type (integer or string type) to date-time structures. |
| 5 | ToDecimalConverts a floating point or integer type to a decimal type. |
| 6 | ToDoubleConverts a type to a double type. |
| 7 | ToInt16Converts a type to a 16-bit integer. |
| 8 | ToInt32Converts a type to a 32-bit integer. |
| 9 | ToInt64Converts a type to a 64-bit integer. |
| 10 | ToSbyteConverts a type to a signed byte type. |
| 11 | ToSingleConverts a type to a small floating point number. |
| 12 | ToStringConverts a type to a string. |
| 13 | ToTypeConverts a type to a specified type. |
| 14 | ToUInt16Converts a type to an unsigned int type. |
| 15 | ToUInt32Converts a type to an unsigned long type. |
| 16 | ToUInt64Converts a type to an unsigned big integer. |
Contoh berikut mengonversi berbagai tipe nilai menjadi tipe string :
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();
}
}
}Ketika kode di atas dikompilasi dan dijalankan, itu menghasilkan hasil sebagai berikut :
75
53.005
2345.7652
True