Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การใช้งานคำสั่ง is ใน C#

is Keyword คืออะไร?

ใช้ตรวจสอบว่า Object สามารถ Cast เป็น Type ที่กำหนดได้หรือไม่ คืนค่า bool

  • Type Testing: obj is Type
  • Pattern Matching (C# 7+): obj is Type variable
  • Constant Pattern: obj is null, obj is 5
  • Relational Patterns (C# 9+): x is > 0

ตัวอย่างพื้นฐาน: Type Testing


using System;

class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class PermanentEmployee : Employee
{
    public decimal AnnualSalary { get; set; }
}

class ContractEmployee : Employee
{
    public decimal HourlyRate { get; set; }
}

class Program
{
    static void Main()
    {
        Employee emp = new PermanentEmployee { Id = 1, Name = "Martin", AnnualSalary = 50000 };
        
        // 1. Base Type Check
        if (emp is Employee)
            Console.WriteLine($"{emp.Name} is Employee"); // True
        
        // 2. Actual Type Check
        if (emp is PermanentEmployee)
            Console.WriteLine($"{emp.Name} is PermanentEmployee"); // True
        
        // 3. Sibling Type Check
        if (emp is ContractEmployee)
            Console.WriteLine($"{emp.Name} is ContractEmployee"); // False
        else
            Console.WriteLine($"{emp.Name} is NOT ContractEmployee");
        
        Console.ReadKey();
    }
}

Pattern Matching (C# 7+) - Type Pattern


// แบบเก่า: Check แล้ว Cast
if (emp is PermanentEmployee)
{
    var perm = (PermanentEmployee)emp;
    Console.WriteLine(perm.AnnualSalary);
}

// แบบใหม่: Type Pattern - Declare Variable ทันที
if (emp is PermanentEmployee perm)
{
    Console.WriteLine($"Salary: {perm.AnnualSalary}"); // perm ใน Scope นี้
}

// Switch Expression (C# 8+)
string GetDescription(Employee e) => e switch
{
    PermanentEmployee p => $"Permanent: {p.AnnualSalary:C}/year",
    ContractEmployee c => $"Contract: {c.HourlyRate:C}/hour",
    _ => "Unknown"
};

Constant Pattern & Relational Patterns (C# 9+)


object obj = "Hello";

// Constant Pattern
if (obj is null) Console.WriteLine("Null");
if (obj is "Hello") Console.WriteLine("It's Hello");
if (obj is 42) Console.WriteLine("It's 42"); // Boxing then compare

// Relational Patterns
int score = 85;
string grade = score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};

// Property Patterns
var person = new { Name = "John", Age = 25 };
if (person is { Age: >= 18, Name: "John" })
    Console.WriteLine("Adult John");

is vs as vs Cast

Operatorคืนค่าExceptionใช้เมื่อไหร่
isboolไม่มีCheck Type ก่อน Cast (Safe)
asType or nullไม่มีCast Reference/Nullable Type แบบ Safe
(Type)objTypeInvalidCastExceptionมั่นใจว่า Cast ได้ (Performance)

// as + null check (Pattern แบบเก่า)
var perm = emp as PermanentEmployee;
if (perm != null) { ... }

// is pattern (Modern, Recommended)
if (emp is PermanentEmployee perm) { ... }

// Cast (เมื่อแน่ใจ)
var perm = (PermanentEmployee)emp; // Throw ถ้าไม่ใช่

is not Pattern (C# 9+)


// Negative Pattern
if (obj is not null) { ... } // เทียบเท่า obj != null

// Not Pattern
if (input is not (>= 0 and <= 100)) 
    throw new ArgumentOutOfRangeException();