Favicon

Constant pattern

Peponi1/8/20252m

C#
SyntaxKeywordPattern

1. Introduction

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

여기서는 식 결과가 지정된 상수와 같은지 확인할 수 있는 상수 패턴을 설명한다. 상수 패턴에는 상수 형식으로 변환할 수 있는 형식을 사용할 수 있다.

2. Example

is 식
int foo = 7;
 
if (foo is 7) Console.WriteLine("foo is 7");
else Console.WriteLine("foo is not 7");
 
/* output:
foo is 7
*/
switch 식
int foo = 7;
 
Console.WriteLine(foo switch
{
    7 => "foo is 7",
    _ => "foo is not 7"
});
 
/* output:
foo is 7
*/
switch 문
int foo = 7;
string writeString = string.Empty;
 
switch (foo)
{
    case 7:
        writeString = "foo is 7";
        break;
 
    default:
        writeString = "foo is not 7";
        break;
}
 
Console.WriteLine(writeString);
 
/* output:
foo is 7
*/

null 체크를 수행하는 경우, is 연산자를 사용하면 오버로드같음 연산자 (==)가 호출되지 않도록 보장된다.

public class Foo
{
    public static bool operator ==(Foo a, Foo b) => false;
    public static bool operator !=(Foo a, Foo b) => false;
}
 
Foo? foo = null;
 
if (foo == null) Console.WriteLine("== null");
if (foo is null) Console.WriteLine("is null");
 
/* output:
is null
*/

3. 참조 자료