Page cover image

Boxing and Unboxing

สุชัญญา คดดี 650710097

Boxing คืออะไร

Boxing คือกระบวนการแปลงตัวแปรชนิด value type (เช่น char, int) ไปเป็นตัวแปรชนิด reference type (เช่น object)

  • การสร้างวัตถุใหม่: ในการBoxing คอมไพเลอร์จะสร้างวัตถุใหม่ขึ้นมาบน heap เพื่อเก็บค่าของ value type นั้น

หลักการทำงานของ Boxing

  • ก่อนการBoxingนั้น ค่าของValue typeเช่น int, float, char จะถูกจัดเก็บใน Stack ในขณะที่Reference typeเช่น object จะถูกจัดเก็บใน Heap memory

ตัวอย่างการใช้งาน และเปรียบเทียบกับภาษาอื่น

using System;

class Program
{
    static void Main()
    {
        int originalValue = 23;
        object boxedValue = originalValue;
    }
}

การAuto Boxing

Autoboxing เป็นการทำให้เกิดการ Boxing โดยอัตโนมัติในบางกรณี โดยเฉพาะชนิดข้อมูลที่ต้องการใช้ประเภทข้อมูลที่เป็นReference Type เช่น ArrayList ซึ่งสามารถเก็บประเภทข้อมูลValue Typeได้

ตัวอย่างการAutoboxing

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<object> list = new List<object>();

        list.Add(42);
    }
}

Unboxing คืออะไร

Unboxing หมายถึงการแปลงค่าแบบ Boxing กลับไปยังประเภทValue Typeจากประเภทข้อมูลที่เป็นReference Type

การแปลงนี้ต้องทำอย่างชัดเจน: หมายความว่าโปรแกรมเมอร์ต้องระบุอย่างชัดเจนว่าต้องการแปลงข้อมูลจากชนิดหนึ่งไปอีกชนิดหนึ่ง

หลักการทำงานของ Unboxing

  • การ Unboxing จะนำกระบวนการ Boxing ที่เป็น Reference Type มาแปลงค่ากลับเป็น Value Type

using System;

class Program
{
    static void Main()
    {
        // Boxing
        int num = 23;
        object boxedNum = num;

        // Unboxing
        int unboxedNum = (int)boxedNum; 

        Console.WriteLine($"Original Number: {num}");
        Console.WriteLine($"Boxed Number: {boxedNum}");
        Console.WriteLine($"Unboxed Number: {unboxedNum}");
    }
}

ตัวอย่างการใช้งาน และเปรียบเทียบกับภาษาอื่น

using System;

class Program
{
    static void Main()
    {
        int originalValue = 23;
        object boxedValue = originalValue;
        int unboxedValue = (int)boxedValue;
    }
}

Slide & Presentation Video

Video Presentation

Slide Presentation

แหล่งอ้างอิง(Reference)

GeeksforGeeks. (n.d.). Boxing and Unboxing in C#. Retrieved from

Microsoft Docs. (n.d.). Boxing and Unboxing. Retrieved from

JavaTpoint. (n.d.). Autoboxing and Unboxing in Java. Retrieved from

SaladPuk. (n.d.). C# 101: Tips on Boxing and Unboxing. Retrieved from

Last updated