C#의 알아두면 편할 기능(1/3)
작성 2019년 12월 22일 김태겸
1. Switch 식 (C# 8.0 추가)
C# 8.0 에 추가된 Switch 식을 사용할 경우 case 및 break 키워드를 반복적으로 사용하고, 중괄호를 적용해야 할 경우의 수가 줄어듭니다. 예시를 들어 다음과 같은 enum 열거형이 있을경우
public enum Color
{
    Red,
    Green,
    Blue
}
기존의 Switch 문을 사용할 경우 다음과 같으나,
public static RGBColor GetColor(Color color)
{
    switch(color)
    {
        case Color.Red :
            return new RGBColor(0xff, 0x00, 0x00);
        case Color.Green :
            return new RGBColor(0x00, 0xff, 0x00);
        case Color.Blue :
            return new RGBColor(0x00, 0x00, 0xff);
        default :
            throw new ArgumentException(message : "invalid enum value", paramName : nameof(color));
    }
}
Switch식을 사용할 경우
public static RGBColor GetColor(Color color) =>
    color switch 
    {
        Color.Red => new RGBColor(0xff, 0x00, 0x00),
        Color.Green => new RGBColor(0x00, 0xff, 0x00),
        Color.Blue => new RGBColor(0x00, 0x00, 0xff),
        _            => throw new ArgumentException(message : "invalid enum value", paramName : nameof(color)),
    };
여기서 몇가지 개선 사항을 확인하면
- 변수가 switch 키워드 앞에 옵니다.
- case 및 : 요소가 =>로 대체되었습니다.
- default 가 _ 무시항목으로 대체되었습니다.
- 본문이 문이 아닌 식입니다.
2. Using 선언 (C# 8.0 추가)
using 선언은 using 키워드 뒤에 오는 변수 선언으로, using 선언은 선언되는 변수를 바깥쪽 범위의 끝에서 삭제하라고 컴파일러에 알립니다.
텍스트 파일을 쓰는 다음 코드를 예시로 보겠습니다.
- 기존 using 문의 경우
    static int WriteLinesToFile(IEnumerable<string> lines) { // We must declare the variable outside of the using block // so that it is in scope to be returned. int skippedLines = 0; using (var file = new System.IO.StreamWriter("WriteLines2.txt")) { foreach (string line in lines) { if (!line.Contains("Second")) { file.WriteLine(line); } else { skippedLines++; } } } // file is disposed here return skippedLines; }
- using 선언의 경우
    static int WriteLinesToFile(IEnumerable<string> lines) { using var file = new System.IO.StreamWriter("WriteLines2.txt"); // Notice how we declare skippedLines after the using statement. 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 }두 코드 모두 컴파일러가 Dispose()를 호출하며, using 문의 식을 삭제할 수 없는 경우 컴파일러에서 오류를 생성합니다. 
3. Null 병합 할당 (C# 8.0 추가)
C# 8.0에서 null 병합 할당 연산자 ??=가 도입되었습니다.
??= 연산자를 이용하여 왼쪽 피연산자가 null로 계산이 되는 경우 오른쪽 피연산자의 값을 왼쪽 피연산자에 대입할 수 있습니다.
List<int> numbers = null;
int? i = null;
numbers ??= new List<int>();
numbers.Add(i ??= 17);
numbers.Add(i ??= 20);
Console.WriteLine(string.Join(" ", numbers));  // output: 17 17
Console.WriteLine(i);  // output: 17
