Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# is 키워드란? 개념부터 실전 예제까지 완벽 정리

C#에서 is 키워드란?

C#의 is 키워드는 특정 객체가 지정한 형식으로 캐스팅(형 변환)이 가능한지 검사할 때 사용하는 연산자입니다. 연산 결과는 항상 bool(Boolean) 타입으로 반환되며, 형 변환이 가능하면 true, 불가능하면 false를 리턴합니다.

특히 상속 관계에서 객체의 실제 타입을 확인하거나, 다운캐스팅을 수행하기 전에 안전성을 검증하는 용도로 널리 활용됩니다.

is 키워드 사용 예제

아래 예제는 기본 클래스인 Employee와 이를 상속하는 PermanentEmployee, ContractEmployee 클래스를 통해 is 키워드의 동작 방식을 보여줍니다.

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");
            }
            else{
                Console.WriteLine(emp.Name + " is not Employee");
            }
            // 실제 객체가 PermanentEmployee 타입이므로 true 반환
            if (emp is PermanentEmployee){
                Console.WriteLine(emp.Name + " is PermanentEmployee");
            }
            else{
                Console.WriteLine(emp.Name + " is not PermanentEmployee");
            }
            // PermanentEmployee 객체는 ContractEmployee로 변환될 수 없으므로 false 반환
            if (emp is ContractEmployee){
                Console.WriteLine(emp.Name + " is ContractEmployee");
            }
            else{
                Console.WriteLine(emp.Name + " is not ContractEmployee");
            }
        }
    }
    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

결과 분석

  • emp is Employee → true: PermanentEmployeeEmployee를 상속하는 파생 클래스이므로 기본 타입으로 변환이 가능합니다.
  • emp is PermanentEmployee → true: 변수는 Employee 타입으로 선언되었지만, 실제 참조하는 객체는 PermanentEmployee이기 때문입니다.
  • emp is ContractEmployee → false: PermanentEmployeeContractEmployee는 서로 형제 관계에 있어 서로 간의 형 변환이 불가능합니다.

참고: C# 7.0의 is 패턴 매칭

C# 7.0부터는 is 키워드와 함께 패턴 매칭(pattern matching)을 사용할 수 있습니다. 타입 검사와 동시에 형 변환된 변수를 선언할 수 있어 코드가 더욱 간결해집니다.

if (emp is PermanentEmployee pe){
    Console.WriteLine($"{pe.Name}의 연봉: {pe.AnnualSalary}");
}

이처럼 is 키워드는 단순한 타입 검사를 넘어, 안전하고 가독성 높은 형 변환 코드를 작성하는 데 필수적인 도구입니다.