C# 7.0 (.NET Framework 4.7 / .NET Core 2.0)에서 도입된 문법과 기능에 대한 빠른 참조 가이드입니다.
out 변수 선언
메서드 호출 매개변수 목록 안에서 직접 out 변수를 인라인으로 선언합니다:
// C# 7 이전:
int result;
if (int.TryParse(input, out result)) { ... }
// C# 7 이후:
if (int.TryParse(input, out int result))
{
Console.WriteLine($"Parsed number: {result}");
}
// 불필요한 out 매개변수는 _로 버리기 (Discards)
if (int.TryParse(input, out _))
{
Console.WriteLine("Input is valid numeric");
}
패턴 매칭 (Pattern Matching)
is를 사용한 형식 패턴
public void PrintArea(object shape)
{
if (shape is Circle c)
{
Console.WriteLine($"Circle area: {Math.PI * c.Radius * c.Radius}");
}
else if (shape is Rectangle r)
{
Console.WriteLine($"Rectangle area: {r.Width * r.Height}");
}
}
패턴 및 when 절을 지원하는 Switch 문
switch (shape)
{
case Circle c:
Console.WriteLine($"Circle with radius {c.Radius}");
break;
case Rectangle r when r.Width == r.Height:
Console.WriteLine($"Square {r.Width} x {r.Height}");
break;
case Rectangle r:
Console.WriteLine($"Rectangle {r.Width} x {r.Height}");
break;
case null:
throw new ArgumentNullException(nameof(shape));
default:
Console.WriteLine("Unknown shape");
break;
}
튜플 및 분해 (Tuples & Deconstruction)
이전 버전 타깃의 경우 System.ValueTuple 패키지가 필요합니다:
이름이 지정된 튜플 반환
(string First, string Last, int Age) GetUser()
{
return ("Alice", "Smith", 30);
}
var user = GetUser();
Console.WriteLine($"{user.First} is {user.Age} years old");
튜플 분해 (Deconstruction)
// 개별 변수로 분해
var (first, last, age) = GetUser();
// 또는 기존 변수에 할당
string f, l;
int a;
(f, l, a) = GetUser();
로컬 함수 (Local Functions)
부모 함수 스코프 내부에 중첩된 헬퍼 메서드를 선언합니다:
public int Factorial(int n)
{
if (n < 0) throw new ArgumentException("Negative value", nameof(n));
return Calculate(n);
int Calculate(int x)
{
return x <= 1 ? 1 : x * Calculate(x - 1);
}
}
리터럴 구문 개선
// 자릿수 구분 기호 (_)
int million = 1_000_000;
long hexMask = 0xFF_EC_00_12;
// 2진수 리터럴 (0b)
byte byteFlag = 0b1010_0110;
ref 로컬 변수 및 반환
복사된 값 대신 메모리 저장 위치에 대한 참조를 반환합니다:
public ref int Find(int target, int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == target) return ref numbers[i];
}
throw new IndexOutOfRangeException();
}
int[] array = { 10, 20, 30 };
ref int val = ref Find(20, array);
val = 99; // array[1] becomes 99
식 본문 멤버 (Expression-Bodied Members)
생성자, 종료자, 속성 접근자로 확장된 식 본문 문법:
class Item
{
private string _name;
// Expression-bodied constructor
public Item(string name) => _name = name ?? throw new ArgumentNullException(nameof(name));
// Expression-bodied property accessor
public string Name
{
get => _name;
set => _name = value ?? "default";
}
}