Boxing chuyển value type thành object type.
int x = 50; object ob = x; // boxing
Giá trị trên stack copy sang object trên heap. Unboxing là ngược lại.
Boxing hữu ích lưu value type trong heap garbage-collected. Là implicit conversion.
Ví dụ
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
static void Main() {
int x = 50;
object ob = x;
x = 100;
// Thay đổi x không ảnh hưởng ob
Console.WriteLine("Value Type = {0}", x);
Console.WriteLine("Object Type = {0}", ob);
}
}
Unboxing: object trên heap copy về value type trên stack. Explicit conversion, ngược với boxing implicit.