แน่นอน 😎 มาลงลึกเรื่อง C# Type Casting พร้อมตัวอย่างและคำอธิบายทีละขั้นตอน
🔹 C# Type Casting – การแปลงชนิดข้อมูล
Type Casting คือการแปลงค่าจาก ชนิดข้อมูลหนึ่งไปเป็นอีกชนิดหนึ่ง ใน C# เราสามารถทำได้หลายวิธี ขึ้นอยู่กับความเข้ากันได้ของชนิดข้อมูล
1️⃣ Implicit Casting (การแปลงอัตโนมัติ)
เงื่อนไข:
-
การแปลงชนิดที่ ปลอดภัย
-
ไม่มีข้อมูลสูญหาย
ตัวอย่าง:
int i = 100;
double d = i; // แปลงจาก int -> double อัตโนมัติ
Console.WriteLine(d); // 100
คำอธิบาย:
-
int
มีขนาดเล็กกว่าdouble
-
C# แปลงให้เองโดยไม่ต้องใช้คำสั่งพิเศษ
2️⃣ Explicit Casting (การแปลงโดยบังคับ)
เงื่อนไข:
-
การแปลงชนิดที่ อาจทำให้ข้อมูลสูญหาย
-
ต้องใช้เครื่องหมาย
(type)
ตัวอย่าง:
double d = 123.45;
int i = (int)d; // แปลง double -> int (ตัดทศนิยม)
Console.WriteLine(i); // 123
คำอธิบาย:
-
การบังคับแปลงทำให้ทศนิยมถูกตัดทิ้ง
-
ต้องระวังข้อมูลสูญหาย
3️⃣ Using Convert
Class
Convert
ช่วยแปลงชนิดข้อมูลอย่างปลอดภัย
string str = "123";
int i = Convert.ToInt32(str);
Console.WriteLine(i + 1); // 124
bool b = Convert.ToBoolean("true");
Console.WriteLine(b); // True
ข้อดี:
-
แปลงจาก string เป็น int, double, bool ได้
-
ปลอดภัยกว่า explicit cast
4️⃣ Using Parse
และ TryParse
Parse
– แปลง string เป็นชนิดอื่น
string s = "3.14";
double d = double.Parse(s);
Console.WriteLine(d); // 3.14
ข้อควรระวัง:
-
ถ้า string ไม่ใช่ตัวเลข จะเกิด Exception
TryParse
– แปลงแบบปลอดภัย
string s = "abc";
bool success = int.TryParse(s, out int result);
Console.WriteLine(success); // False
Console.WriteLine(result); // 0 (default)
ข้อดี:
-
ป้องกัน Exception
-
รู้ผลการแปลงผ่าน
success
5️⃣ Casting กับ Object / Class
Upcasting (ชั้นบน)
class Animal { public void Speak() => Console.WriteLine("Animal speaks"); }
class Dog : Animal { public void Bark() => Console.WriteLine("Woof!"); }
Dog dog = new Dog();
Animal a = dog; // Upcast เป็น Animal
a.Speak(); // Animal speaks
Downcasting (ชั้นล่าง)
Animal a = new Dog();
Dog d = (Dog)a; // Downcast ต้อง explicit
d.Bark(); // Woof!
คำเตือน:
-
Downcast ต้องแน่ใจว่า object เป็น instance ของ subclass
-
หากไม่ใช่ จะเกิด InvalidCastException
6️⃣ Using as
และ is
Keyword
-
as
– แปลง object ถ้าไม่ได้ type จะคืนค่า null
Animal a = new Dog();
Dog d = a as Dog;
if(d != null) d.Bark();
-
is
– ตรวจสอบชนิดก่อน cast
Animal a = new Dog();
if(a is Dog d)
{
d.Bark();
}
ข้อดี:
-
ปลอดภัยกว่า explicit cast
-
ป้องกัน InvalidCastException
7️⃣ Summary
วิธี | ใช้กับ | ความปลอดภัย | ตัวอย่าง |
---|---|---|---|
Implicit Cast | int → double | ปลอดภัย | double d = 10; |
Explicit Cast | double → int | อาจสูญข้อมูล | int i = (int)3.14; |
Convert | string → int/double | ปลอดภัย | int i = Convert.ToInt32("123"); |
Parse / TryParse | string → number | TryParse ปลอดภัย | int.TryParse("123", out int x); |
as / is | object / class | ปลอดภัย | Dog d = a as Dog; |
💡 Tip:
-
ใช้ implicit cast เมื่อปลอดภัย
-
ใช้ Convert / TryParse กับ string
-
ใช้ as / is กับ class inheritance