Boxing และ Unboxing
C# มีการเชื่อมโยงระหว่าง Value Type (struct, int, bool) และ Reference Type (object, class)
- Boxing: แปลง Value Type → Object Type (implicit conversion)
- Unboxing: แปลง Object Type → Value Type (explicit conversion ต้อง cast)
ตารางเปรียบเทียบ
| ลำดับ | หัวข้อ | Boxing | Unboxing |
|---|---|---|---|
| 1 | การทำงาน | ทำให้ object type อ้างอิง value type | ดึงค่า value จาก boxed object |
| 2 | หน่วยความจำ | คัดลอกค่าจาก Stack ไป Heap | คัดลอกค่าจาก Heap กลับ Stack |
| 3 | ประเภทการแปลง | Implicit conversion (อัตโนมัติ) | Explicit conversion (ต้อง cast เอง) |
ตัวอย่างโค้ด (Java/C#)
public class JavaTester {
public static void main(String[] args) {
int val = 119;
// Boxing
Object o = val;
// เปลี่ยนค่า val
val = 120;
// Unboxing
int x = (int)o;
System.out.println("Value of x is " + x); // 119
System.out.println("Value type of val is " + val); // 120
System.out.println("Object type of val is " + o); // 119
}
}ผลลัพธ์
Value of x is 119 Value type of val is 120 Object type of val is 119
คำอธิบาย: Boxing เก็บค่า 119 ไว้ใน object o แล้ว val เปลี่ยนเป็น 120 Unboxing ดึงค่าจาก o ได้ 119 (ค่าเดิม) แสดงว่า Boxing สร้าง copy ใหม่ใน Heap