C# 5 이후 버전들에서 꼭 알아야 할 문법들을 한국어로 정리해보겠습니다. 각 버전별로 중요한 문법과 기능을 간략히 설명하겠습니다.
C# 6.0 (2015)
Auto-property Initializers
속성 초기화자: 속성을 선언할 때 초기 값을 설정할 수 있습니다.
public string Name { get; set; } = "Default Name";
Expression-bodied Members
표현식 본문 멤버: 메서드, 속성, 인덱서, 최종자 등을 간결하게 작성할 수 있습니다.
public string FullName => $"{FirstName} {LastName}";
Null-conditional Operator
널 조건부 연산자: 객체가 널인지 확인하고, 널이 아니면 특정 속성이나 메서드를 호출합니다.
int? length = customers?.Length;
String Interpolation
문자열 보간: 문자열 내에 변수를 쉽게 삽입할 수 있습니다.
string message = $"Hello, {name}. You are {age} years old.";
nameof Operator
nameof 연산자: 변수나 속성의 이름을 문자열로 반환합니다.
void PrintName(string name)
{
if (name == null) throw new ArgumentNullException(nameof(name));
}
C# 7.0 - 7.3 (2017-2018)
Out Variables
out 변수: 메서드 호출 시 out 매개변수를 선언할 때 변수를 동시에 선언할 수 있습니다.
if (int.TryParse(input, out int result))
{
Console.WriteLine(result);
}
Tuples and Deconstruction
튜플과 분해: 여러 값을 하나의 변수에 저장하고, 이를 쉽게 분해할 수 있습니다.
var person = (name: "Alice", age: 25);
var (name, age) = person;
Pattern Matching
패턴 매칭: switch 문과 is 연산자를 사용하여 복잡한 조건을 간결하게 표현할 수 있습니다.
switch (obj)
{
case int n when n > 0:
Console.WriteLine("Positive number");
break;
case string s:
Console.WriteLine($"String: {s}");
break;
case null:
Console.WriteLine("Null");
break;
default:
Console.WriteLine("Unknown");
break;
}
Local Functions
지역 함수: 메서드 내부에 다른 메서드를 정의할 수 있습니다.
public int Calculate(int x)
{
return Add(x, 5);
int Add(int a, int b) => a + b;
}
Ref Locals and Returns
ref 지역 변수와 반환: 메서드에서 참조를 반환할 수 있습니다.
ref int Find(int[] numbers, int target)
{
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == target)
return ref numbers[i];
}
throw new InvalidOperationException("Not found");
}
public static string GetDayType(DayOfWeek day) => day switch
{
DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend",
DayOfWeek.Monday => "Start of work week",
_ => "Weekday"
};