Toán tử is trong C# kiểm tra kiểu runtime của đối tượng có tương thích với kiểu cho trước hay không (type testing). Trả về true/false.
Cú pháp:
expr is type
Ví dụ: Kiểm tra kiểu đối tượng
using System;
class One { }
class Two { }
public class Demo
{
public static void Test(object obj)
{
if (obj is One)
{
Console.WriteLine("Class One");
One x = (One)obj; // Safe cast sau khi check
}
else if (obj is Two)
{
Console.WriteLine("Class Two");
Two y = (Two)obj;
}
else
{
Console.WriteLine("None of the classes!");
}
}
public static void Main()
{
One o1 = new One();
Two t1 = new Two();
Test(o1);
Test(t1);
Test("str");
Console.ReadKey();
}
}
Kết quả
Class One
Class Two
None of the classes!
C# 7+ Pattern Matching: Gộp check và cast: if (obj is One x) → biến x có scope trong block if.
if (obj is One x) { Console.WriteLine(x); } // x available here