Favicon

Type, declaration patterns

Peponi1/8/20253m

C#
SyntaxKeywordPattern

1. Introduction

다음 C# 식과 문은 패턴을 지원한다.

여기서는 다음 패턴을 설명한다.

  • 형식 패턴 : 형식 확인
  • 선언 패턴 : 형식 확인 및 성공 시 결과를 변수에 할당

TIP

특정 객체가 T 형식임을 확인하는 경우, 아래 형식 조건 중 하나를 만족하면 true가 반환된다.

2. 형식 패턴

식의 형식을 확인하려는 경우 다음과 같이 형식 패턴을 사용할 수 있다.

Declaration
namespace TypePattern
{
    public interface Common { }
 
    public class Foo : Common { }
    public class Bar : Common { }
}
is 식
List<Common> collection = [new Foo(), new Bar()];
 
foreach (var item in collection)
{
    if (item is Foo || item is Bar)
    {
        Console.WriteLine(item.ToString());
    }
}
 
/* output:
TypePattern.Foo
TypePattern.Bar
*/
switch 식
List<Common> collection = [new Foo(), new Bar()];
 
foreach (var item in collection)
{
    Console.WriteLine(GetName(item));
}
 
string GetName(Common item)
{
    return item switch
    {
        Foo => item.ToString()!,
        Bar => item.ToString()!,
        _ => string.Empty
    };
}
 
/* output:
TypePattern.Foo
TypePattern.Bar
*/
switch 문
List<Common> collection = [new Foo(), new Bar()];
 
foreach (var item in collection)
{
    Console.WriteLine(GetName(item));
}
 
string GetName(Common item)
{
    switch (item)
    {
        case Foo:
        case Bar:
            return item.ToString()!;
 
        default:
            return string.Empty;
    }
}
 
/* output:
TypePattern.Foo
TypePattern.Bar
*/

3. 선언 패턴

식의 형식을 확인하고 변수를 할당하려는 경우 다음과 같이 선언 패턴을 사용할 수 있다.

Declaration
namespace DeclarationPattern
{
    public interface Common { }
 
    public class Foo : Common { }
    public class Bar : Common { }
}
is 식
List<Common> collection = [new Foo(), new Bar()];
 
foreach (var item in collection)
{
    if (item is Foo foo) Console.WriteLine(foo);
    else if (item is Bar bar) Console.WriteLine(bar);
}
 
/* output:
DeclarationPattern.Foo
DeclarationPattern.Bar
*/
switch 식
List<Common> collection = [new Foo(), new Bar()];
 
foreach (var item in collection)
{
    Console.WriteLine(GetName(item));
}
 
string GetName(Common item)
{
    return item switch
    {
        Foo foo => foo.ToString()!,
        Bar bar => bar.ToString()!,
        _ => string.Empty
    };
}
 
/* output:
DeclarationPattern.Foo
DeclarationPattern.Bar
*/
switch 문
List<Common> collection = [new Foo(), new Bar()];
 
foreach (var item in collection)
{
    Console.WriteLine(GetName(item));
}
 
string GetName(Common item)
{
    switch (item)
    {
        case Foo foo:
            return foo.ToString()!;
        case Bar bar:
            return bar.ToString()!;
 
        default:
            return string.Empty;
    }
}
 
/* output:
DeclarationPattern.Foo
DeclarationPattern.Bar
*/

4. 참조 자료