다음 내용을 입력한 후 실행해 보세요.
패턴 매칭을 if 문으로 표현: PatternMatchingIf.cs
using System;
namespace PatternMatchingIf
{
class Shape { }
class Rectangle : Shape
{
public string Name { get; set; } = "사각형";
}
class PatternMatchingIf
{
static void Main() => ShowShape(new Rectangle());
static void ShowShape(Shape shape)
{
//① if 구문을 사용한 패턴 매칭
if (shape is Rectangle r)
{
Console.WriteLine(r.Name);
}
}
}
}
실행 결과
사각형
Main() 메서드가 시작되자마자 ShowShape() 메서드에 매개변수로 Rectangle 클래스의 인스턴스를 넘겼습니다. 이를 받는 ShowShape() 메서드의 shape 변수는 그 패턴(성질)이 Shape 클래스와 일치하기에 ①의 r 변수에 담겨 사용됩니다.
ShowShape() 메서드에는 Rectangle 클래스의 인스턴스가 전달될 때만 if 문이 실행됩니다.