Is operator
Peponi │ 11/13/2024 │ 5m
C#
SyntaxOperator
Is operator
11/13/2024
5m
Peponi
C#
SyntaxOperator
1. Introduction
is
연산자는 주어진 식을 이용하여 다음 작업을 수행한다.
- 형식 일치 여부 확인
- 패턴 일치 여부 확인
is
식은 아래와 같이 표현한다.
if(expression is type) // 1
if(expression is pattern) // 2
expression
은 값을 반환하는 식,type
은 형식 또는 형식 매개 변수의 이름이다.
여기서type
은 무명 메서드 또는 람다 식으로 표현할 수 없다.expression
은 값을 반환하는 식,pattern
은 일치 여부를 확인할 패턴이다.
2. 형식 일치 여부 확인
is
연산자를 이용하여 형식 일치 여부를 확인할 수 있다. 주어진 식이 null
이 아닌 경우, is
연산자는 다음 조건 중 하나를 만족하면 true
를 반환한다.
T
orT?
(HasValue == true
인 경우)T
의 파생 형식T
인터페이스 구현T
형식으로 boxing 또는 unboxing 가능한 경우
이 때, is
연산자는 숫자 변환, 사용자 정의 변환에 대해서는 고려하지 않는다.
2.1. T or T?
다음은 주어진 식이 T
또는 T?
임을 확인한다.
int? foo = 1;
Console.WriteLine(foo is int);
Console.WriteLine(foo is int?);
foo = null;
Console.WriteLine(foo is int);
Console.WriteLine(foo is int?);
/* output:
True
True
False
False
*/
2.2. T의 파생 형식
다음은 주어진 식이 T
의 파생 형식임을 확인한다.
public class Base { }
public class Derived : Base { }
var derived = new Derived();
Console.WriteLine(derived is Base);
Console.WriteLine(derived is Derived);
/* output:
True
True
*/
Base
객체의 경우, Derived
에 대해 false
를 반환하게 된다.
var @base = new Base();
Console.WriteLine(@base is Base);
Console.WriteLine(@base is Derived);
/* output:
True
False
*/
2.3. T 인터페이스 구현
다음은 주어진 식이 T
인터페이스를 구현한 형식임을 확인한다.
public interface Interface { }
public class Class : Interface { }
var foo = new Class();
Console.WriteLine(foo is Interface);
/* output:
True
*/
2.4. T 형식으로 boxing 또는 unboxing 가능한 경우
다음은 주어진 식에 대해 is
연산자가 boxing, unboxing을 확인한다는 것을 보여준다.
int foo = 1;
object fooBoxed = foo;
Console.WriteLine(foo is object);
Console.WriteLine(fooBoxed is int);
/* output:
True
True
*/
2.5. 숫자 변환, 사용자 정의 변환
다음은 주어진 식에 대해 is
연산자가 숫자 변환, 사용자 정의 변환에 대해서는 고려하지 않는 것을 보여준다.
byte foo = 1;
int bar = foo;
Console.WriteLine(foo is int);
/* output:
False
*/
public readonly struct Byte
{
private readonly byte _value;
public Byte(byte value) => _value = value;
public static explicit operator byte(Byte value) => value._value;
public static implicit operator Byte(byte value) => new(value);
}
byte foo = 1;
Byte bar = foo;
Console.WriteLine(foo is Byte);
/* output:
False
*/
3. 패턴 일치 여부 확인
is
연산자를 이용하여 패턴 일치 여부를 확인할 수 있다. 여기서는 간단한 사례를 보여준다.
int foo = 7;
if (foo is 7) Console.WriteLine("foo is 7");
else Console.WriteLine("foo is not 7");
/* output:
foo is 7
*/
int foo = 7;
if (foo is < 0) Console.WriteLine("foo < 0");
else if (foo is < 5) Console.WriteLine("foo < 5");
else if (foo is < 10) Console.WriteLine("foo < 10");
/* output:
foo < 10
*/
자세한 사항은 아래 항목을 참조한다.