typeof(T)
- Operator: ใช้กับ **Type Name** (Compile-time)
- Return:
System.Type
- ไม่ต้องมี Instance
Type t = typeof(string); // typeof(DemoClass)
GetType()
- Method: เรียกบน **Object Instance** (Runtime)
- Return:
System.Type ของ Instance จริง (Polymorphism)
- Defined ใน
System.Object
object obj = "hello";
Type t = obj.GetType(); // typeof(string)
is Keyword
- Pattern Matching / Type Check
- Return:
bool
- ใช้ใน Condition
object obj = "hello";
if (obj is string) { ... } // true
if (obj is int) { ... } // false
ตัวอย่างเปรียบเทียบ
class Demo { }
var demo = new Demo();
Console.WriteLine($"typeof: {typeof(Demo)}"); // ConsoleApp.Demo
Console.WriteLine($"GetType: {demo.GetType()}"); // ConsoleApp.Demo
Console.WriteLine($"is Demo: {demo is Demo}"); // True
สรุป
| Feature | typeof | GetType() | is |
| ใช้กับ | Type Name | Instance | Instance + Type |
| Return | Type | Type | bool |
| Time | Compile-time | Runtime | Runtime |
| Polymorphism | No | Yes (Actual Type) | Yes |