Boxing และ Unboxingเป็นกระบวนการแปลงข้อมูลจากvalue type เป็นreference type ซึ่งเป็นกระบวนการที่สำคัญในภาษาC# โดยที่กระบวนการนั้นจะแยกกันอย่างชัดเจน ประกอบไปด้วยค่าสามค่า นั้นก็คือ Value Types (int, char, etc), Reference Types (object) และPointer Types. โดยแบ่งเป็นกระบวนการBoxing และ Unbox
Example
usingSystem;publicclassBoxing{staticpublicvoidMain(){intnumber=2024;charletter='C';objecto=number;objectl=letter;number=2000;Console.WriteLine("Value type of val is {0}",number);Console.WriteLine("Object type of letter is {0}",l);Console.WriteLine("Object type of number is {0}",o);}}
Value type of val is 2000
Object type of letter is C
Object type of number is 2024
จากโค้ดด้านบนเป็นกระบวนการBoxing โดยจะแปลงletter ในบรรทัด7 ซึ่งเป็น Value Types (char) และ number ในบรรทัดที่6 ซึ่งเป็น Value Types (int) ให้เป็นreference type number --> o และ letter --> l จากนั้นในบรรทัดที่12จะสาธิตการเปลี่ยนค่าnumber เป็น 2000 จะเห็นได้ว่า output ของค่าที่เก็บเอาไว้แล้วจะไม่เปลี่ยน บรรทัดที่ทำการBoxingคือ 9และ10
จากโค้ด เป็นกระบวนการUnboxingโดยเพิ่มบรรทัดที่12 และ บรรทัดที่13 เป็นการtypecastจากobjectที่ทำการBoxingเอาไว้ให้เป็นvalue typesดังเดิม (letter --> l -->xx)(number --> o --> x)แสดงผลเป็นได้ดั่งoutputข้างต้น
GeeksforGeeks. "Difference between Boxing and Unboxing in C#." GeeksforGeeks, n.d., https://www.geeksforgeeks.org/difference-between-boxing-and-unboxing-in-c/.
Microsoft Learn. "Boxing and Unboxing - C#." Microsoft Learn, n.d., https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/boxing-and-unboxing.
saladpuk. (n.d.). Boxing and Unboxing - C#. saludpuk. Retrieved October 12, 2024, from https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/boxing-and-unboxing
using System;
public class Unbox{
static public void Main()
{
int number = 2024;
char letter = 'C';
object o = number ;
object l = letter ;
int x = (int)o;
char xx = (char)l;
Console.WriteLine("Value type of val is {0}", number);
Console.WriteLine("Object type of letter is {0}", l);
Console.WriteLine("Object type of number is {0}", o);
}
}
Value type of val is 2000
Object type of letter is C
Object type of number is 2024
using System;
public class Program
{
public static void Main()
{
int number = 2024;
object obj = number;
Console.WriteLine(obj);
int originalNumber = (int)obj;
Console.WriteLine("Original number: " + originalNumber);
}
}
public class Main {
public static void main(String[] args) {
int number = 2024;
Object obj = number;
System.out.println("obj.getClass().getName());
int originalNumber = (int) obj;
System.out.println("Original number: " + originalNumber);
}
}
def main():
number = 2024
obj = number
print("obj is an instance of:", type(obj).__name__)
original_number = obj
print("Original number:", original_number)
if __name__ == "__main__":
main()