Java Class.isInstance(obj) ตรวจสอบว่า Object เป็น Instance ของ Class/Interface นั้นหรือ Subclass ใน C# มีหลายวิธีเทียบเท่า
วิธีที่ 1: Pattern Matching `is` (แนะนำ C# 7+)
object obj = "Hello";
bool isString = obj is string; // True
bool isObject = obj is object; // True
bool isInt = obj is int; // False
// With Declaration Pattern (C# 7+)
if (obj is string s)
{
Console.WriteLine(s.Length); // s ใช้ได้ใน Scope นี้
}
// Type Pattern (C# 9+)
bool result = obj is string { Length: > 5 }; // String และ Length > 5
วิธีที่ 2: Type.IsInstanceOfType() (คล้าย Java มากที่สุด)
Type stringType = typeof(string);
object obj = "Hello";
bool isString = stringType.IsInstanceOfType(obj); // True
// เทียบกับ Java: String.class.isInstance(obj)
วิธีที่ 3: Type.IsAssignableFrom() (ตรงข้าม)
// obj.GetType().IsAssignableFrom(typeof(string)) → False
// typeof(string).IsAssignableFrom(obj.GetType()) → True
// ใช้สำหรับ: ตรวจสอบว่า Type A Assignable จาก Type B (B → A)
bool canAssign = typeof(IEnumerable).IsAssignableFrom(typeof(List)); // True
bool canAssign2 = typeof(List).IsAssignableFrom(typeof(IEnumerable)); // False
วิธีที่ 4: as Operator + Null Check
string s = obj as string;
if (s != null) { /* Is String */ }
// C# 7+ Pattern Matching แทนที่ as + null check
if (obj is string s) { /* s ใช้ได้ */ }
วิธีที่ 5: GetType() == typeof() (Exact Type Only - No Inheritance)
bool isExactlyString = obj.GetType() == typeof(string); // False สำหรับ Subclass
bool isStringOrSub = obj is string; // True สำหรับ Subclass
ตารางเปรียบเทียบ
| เมธอด | รองรับ Inheritance | Null Safe | Performance | Syntax |
|---|---|---|---|---|
obj is Type | ใช่ | ใช่ (False) | Fast (JIT Optimized) | Clean |
Type.IsInstanceOfType(obj) | ใช่ | ใช่ (False) | Fast | Reflection Style |
Type.IsAssignableFrom(obj.GetType()) | ใช่ | No (Throws if null) | Fast | Reversed Logic |
obj as Type != null | ใช่ | ใช่ | Fast | Legacy |
obj.GetType() == typeof(Type) | ไม่ (Exact Only) | No (Throws if null) | Fastest | Exact Match |
กรณีใช้งานจริง
- Plugin System: ตรวจสอบ Type ก่อน Cast
- Serialization: ตรวจสอบ Type รองรับ
- Dependency Injection: Validate Service Type
- Message Routing: Route ตาม Message Type
Generic Type Checking
// รันไทม์: ตรวจสอบ Generic Type
public static bool IsGenericListOfT(object obj, Type elementType)
{
var type = obj.GetType();
return type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(List<>) &&
type.GetGenericArguments()[0] == elementType;
}