Kiểu object gán được giá trị mọi kiểu: value type, reference type, predefined, user-defined. Cần chuyển kiểu trước khi gán.
Object Type là base class tối thượng CTS. object alias System.Object.
Value type -> object: boxing. Object -> value type: unboxing.
object obj; obj = 100; // boxing
Ví dụ hoàn chỉnh
using System;
using System.IO;
namespace Demo {
class objectClass { public int x = 200; }
class MyApplication {
static void Main() {
object obj;
obj = 50;
Console.WriteLine(obj); // 50
Console.WriteLine(obj.GetType()); // System.Int32
Console.WriteLine(obj.ToString()); // 50
obj = new objectClass();
objectClass newRef;
newRef = (objectClass)obj; // unboxing
Console.WriteLine(newRef.x); // 200
}
}
}
Kết quả
50 System.Int32 50 200