[C#] 패턴 매칭

Flaming Bun·2025년 7월 25일

C#

목록 보기
31/35

참고 사이트 : https://www.youtube.com/watch?v=ySd_-h_Dapc

https://learn.microsoft.com/ko-kr/dotnet/csharp/fundamentals/functional/pattern-matching

🔥 패턴 매칭

패턴 매칭은 값의 구조, 타입, 조건 등을 검사하고, 일치하는 경우 작업 수행을 보다 간결하고 안전하게 처리할 수 있는 구문을 제공한다.

isswitch 식을 주로 사용한다.


null 검사

null인지 확인하는 패턴으로 is Type으로 검사한다.

예시

int? maybe = 12;

if(maybe is int number)
{
	Console.WriteLine("is number");
}
else
{
	Console.WriteLine("is not number");
}

예시 2

string? something = ReadSomething();

if(something is not null)
{
	Console.WriteLine(something);
}


Type 패턴 매칭

is Type, is AType or BType 등을 이용해 타입이 같은지 확인하는 방법이다.


예시

private void PrintType(object obj)
{
	if(obj is string str)
    {
    	Console.WriteLine($"{str} is string.");
    }
    else if(obj is ICollection collection)
    {
    	Console.WriteLine($"{collection} is ICollection.")
    }
    else if(obj is int or float)
    {
    	Console.WriteLine($"obj's type is {obj.GetType().Name}")
    }
}


Property 패턴 매칭

객체의 여러 속성을 검사할 때 사용한다.


예시


public recond Person(string Name, int Age);

public class PropertyPatternMatching 
{
	private void GreetPerson(Person person)
    {
    	static void Main(string[] args)
        {
        	GreatPerson(new Person("Bob",30)); // Hi Bob !!
            PrintPersonInfo(new Person("Lisa" 25)); // Name: Losa, Age: 25
        }
    
    	switch(person)
        {
        	case {Name: "Alice", Age: 25}:
            	Console.WriteLine("Hi Alice !!");
            	break;
			case {Name: "Bob", Age: 30}:
            	Console.WriteLine("Hi Bob !!");
            	break;
            default:
            	Console.WriteLine("Hi bro !!");
                break;
        }
    }
    
    private void PrintPersonInfo(Person obj)
    {
    	if(obj is Person {Name : string name, Age: >= 18 and <= 65})
        {
        	Console.WriteLine($"Name: {name}, Age: {obj.Age}");
        }
    }
}

0개의 댓글