Type Conversion vs Type Casting ใน C#
ใน C# คำทั้งสองมักใช้แทนกันได้ หมายถึงการแปลงชนิดข้อมูลจากชนิดหนึ่งไปอีกชนิดหนึ่ง แบ่งเป็น 2 รูปแบบ
1. Implicit Conversion (การแปลงโดยนัย)
- เกิดขึ้นอัตโนมัติโดย Compiler
- ปลอดภัย ไม่สูญเสียข้อมูล (No Data Loss)
- ตัวอย่าง: เล็กไปใหญ่ (int → long), Derived → Base Class
int i = 100;
long l = i; // Implicit: int → long
double d = i; // Implicit: int → double
object o = i; // Implicit: int → object (Boxing)
2. Explicit Conversion / Casting (การแปลงแบบชัดเจน)
- ต้องเขียน Cast Operator
(Type)เอง - อาจสูญเสียข้อมูล หรือเกิด Exception ถ้าแปลงไม่ได้
- ตัวอย่าง: ใหญ่ไปเล็ก (double → int), Base → Derived (Unboxing)
double d = 9322.46;
int i = (int)d; // Explicit Cast: double → int (Truncates .46)
Console.WriteLine(i); // 9322
object obj = 123;
int j = (int)obj; // Unboxing
ตัวอย่างโค้ดครบถ้วน
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
double d = 9322.46;
int i;
// Explicit Cast
i = (int)d;
Console.WriteLine($"Double {d} -> Int {i}"); // 9322
// Implicit
long l = i;
Console.WriteLine($"Int {i} -> Long {l}"); // 9322
// Helper Methods (แนะนำให้ใช้แทน Cast ตรงๆ)
string s = "123";
int parsed = int.Parse(s); // Parse String -> Int
bool success = int.TryParse("abc", out int result); // Safe Parse
Console.ReadKey();
}
}
}
ผลลัพธ์
Double 9322.46 -> Int 9322
Int 9322 -> Long 9322
เมธอดช่วยแปลงชนิด (Recommended)
| เมธอด | ใช้เมื่อ | ตัวอย่าง |
|---|---|---|
Convert.ToInt32() | แปลงจาก object/อื่นๆ เป็น int | Convert.ToInt32("123") |
int.Parse() | Parse String -> int (Throw ถ้า Fail) | int.Parse("123") |
int.TryParse() | Parse String -> int (Return bool, Safe) | int.TryParse(s, out int n) |
ToString() | แปลงค่าใดๆ เป็น String | 123.ToString() |
User-Defined Conversions
สามารถสร้าง Implicit/Explicit Operator เองได้ใน Struct/Class
struct Digit
{
public byte Value;
public static implicit operator byte(Digit d) => d.Value;
public static explicit operator Digit(byte b) => new Digit { Value = b };
}