is কীওয়ার্ড
is কীওয়ার্ড ব্যবহার করে যাচাই করা যায় কোনো অবজেক্ট নির্দিষ্ট টাইপে কাস্ট করা যাবে কিনা। রিটার্ন টাইপ bool।
বেসিক সিনট্যাক্স
if (obj is TargetType) { ... }
উদাহরণ: ইনহেরিট্যান্স হায়ারার্কি
using System;
namespace DemoApplication {
class Program {
static void Main() {
Employee emp = new PermanentEmployee {
ID = 1,
Name = "Martin"
};
// বেস টাইপ চেক — true (ডেরাইভড → বেস)
if (emp is Employee) {
Console.WriteLine($"{emp.Name} is Employee");
}
// একচেটিয়া টাইপ চেক — true
if (emp is PermanentEmployee) {
Console.WriteLine($"{emp.Name} is PermanentEmployee");
}
// ভিন্ন ব্রাঞ্চ — false
if (emp is ContractEmployee) {
Console.WriteLine($"{emp.Name} is ContractEmployee");
} else {
Console.WriteLine($"{emp.Name} is NOT ContractEmployee");
}
Console.ReadKey();
}
}
class Employee {
public int ID { get; set; }
public string Name { get; set; }
}
class PermanentEmployee : Employee {
public int AnnualSalary { get; set; }
}
class ContractEmployee : Employee {
public int HourlySalary { get; set; }
}
}
আউটপুট:
Martin is Employee Martin is PermanentEmployee Martin is NOT ContractEmployee
Pattern Matching (C# 7.0+) — is সহ ভেরিয়েবল ডিক্লেয়ারেশন
// পুরানো স্টাইল
if (obj is Employee) {
var emp = (Employee)obj;
Console.WriteLine(emp.Name);
}
// নতুন স্টাইল — টাইপ প্যাটার্ন
if (obj is Employee emp) {
Console.WriteLine(emp.Name); // emp সরাসরি ব্যবহারযোগ্য
}
// প্রপার্টি প্যাটার্ন (C# 8.0+)
if (emp is PermanentEmployee { AnnualSalary: > 50000 }) {
Console.WriteLine("High earner");
}
// সوییচ এক্সপ্রেশন (C# 8.0+)
string GetRole(Employee e) => e switch {
PermanentEmployee p when p.AnnualSalary > 100000 => "Senior",
PermanentEmployee p => "Permanent",
ContractEmployee c => "Contractor",
_ => "Unknown"
};
is vs as vs cast
| অপারেটর | ব্যবহার | Null হলে | রিটার্ন |
|---|---|---|---|
is | টাইপ চেক | false | bool |
as | সেফ কাস্ট | null ফেরত দেয় | TargetType or null |
(Type)obj | ফোর্স কাস্ট | InvalidCastException | TargetType |