C#

Version 8.0.

JSpartner 2022. 5. 12. 19:02

Unity 2021 LTS에 사용되는 C# 8.0에 대해 알아보았습니다.

Microsoft에서 발표한 C#의 새로운 기능은 다음과 같습니다.

https://docs.microsoft.com/ko-kr/dotnet/csharp/whats-new/csharp-8

먼저 C#에서는 switch의 패턴 일치를 표현식(=>)으로 간결하게 구현할 수 있게 해주었습니다.

 

static double GetArea(Shape shape)
{
     // C# 8.0 switch expression
     double area = shape switch
     {
         null        => 0,
         Line _      => 0,
         Rectangle r => r.Width * r.Height,
         Circle c    => Math.PI * c.Radius * c.Radius,
         _           => throw new ArgumentException()
     };
     return area;
}

예제 출처 : https://www.csharpstudy.com/latest/CS8-pattern-matching.aspx

그리고 C# 8.0에는 재귀 패턴이라는 것이 생겼습니다.

C# 8.0에서는 패턴 내에 서브 패턴이 있을 수 있고 호출할 수 있는데, 이를 재귀 패턴이라고 합니다.

아래의 예제를 보면, 먼저 people List 안에 있는 p 가 Student 속성인지 확인하고 있고(패턴 일치),

그 안에서 Graduated가 false이고 Name이 string 형식인지 확인하고 있습니다.(서브 패턴 일치)

 

IEnumerable<string> GetStudents(List<Person> people) 
{
     foreach (var p in people)
     {
         // Recursive pattern (재귀 패턴)
         if (p is Student { Graduated: false, Name: string name })
         {
             yield return name;
         }
     }
}

예제 출처 : https://www.csharpstudy.com/latest/CS8-pattern-matching.aspx

또한, using을 멤버 함수 내에서 호출하여 리소스를 지역적으로 쓰는 것이 가능합니다.

using으로 선언한 변수는 해당 구문이 끝나면 자동으로 해제됩니다.(dispose())

아래의 예제를 보면, using var file은 WriteLinesToFile 함수가 호출될 때만 사용되고,

함수가 끝나면 자동으로 리소스가 해제됩니다.

 
static int WriteLinesToFile(IEnumerable<string> lines)
{
    using var file = new System.IO.StreamWriter("WriteLines2.txt");
    int skippedLines = 0;
    foreach (string line in lines)
    {
        if (!line.Contains("Second"))
        {
            file.WriteLine(line);
        }
        else
        {
            skippedLines++;
        }
    }
    // Notice how skippedLines is in scope here.
    return skippedLines;
    // file is disposed here
}

예제 출처 : https://docs.microsoft.com/ko-kr/dotnet/csharp/whats-new/csharp-8#using-declarations

 

그리고 C# 8.0부터는 비동기 스트림을 생성할 수 있습니다.

이전까지는 async/await을 이용하여 비동기적으로 결과를 한번씩만 받아왔는데,

C# 8.0을 사용하면 연속적인 결과를 비동기적으로 받아올 수 있게 되었습니다.

이 외에도 다양한 내용들이 많아서 한번 문서를 읽어보시는 것을 추천드립니다.

https://docs.microsoft.com/ko-kr/dotnet/csharp/whats-new/csharp-8