Object Type กำหนดค่าได้ทุกประเภท (Value, Reference, Predefined, User-defined) แต่ต้อง Type Conversion ก่อน
Object Type = Base Class สุดท้ายใน CTS object = Alias ของ System.Object
- Value Type -> Object = Boxing
- Object -> Value Type = Unboxing
ตัวอย่าง
object obj; obj = 100; // Boxing
ตัวอย่างสมบูรณ์
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 = (objectClass)obj; // Unboxing
Console.WriteLine(newRef.x); // 200
}
}
}
Output
50 System.Int32 50 200