https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/
Init-only properties
property에 "init" 키워드를 지정할 수 있게 된다.
키워드가 붙은 property는 생성시에만 수정할 수 있으며 그 이후에는 get만을 수행할 수 있다.
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
new Person
{
FirstName = "Scott",
LastName = "Hunter"
}
Init accessors and readonly fields
설명한 init 키워드의 property는 생성자와 마찬가지로 readonly 필드를 수정할 수 있다.
public class Person
{
private readonly string firstName;
private readonly string lastName;
public string FirstName
{
get => firstName;
init => firstName = (value ?? throw new ArgumentNullException(nameof(FirstName)));
}
public string LastName
{
get => lastName;
init => lastName = (value ?? throw new ArgumentNullException(nameof(LastName)));
}
}
Records
init-only property는 property 각각의 불변성을 지키는데 유효하다. 그런데 만약 오브젝트 전체의 불변성이 유지되도록 만들고 싶다면, 해당 클래스를 record로 선언하는 것을 고려해보자.
public data class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
클래스 선언의 "data" 키워드는 해당 클래스를 record로 선언했다는 뜻이다. 이는 생성 이후 이 클래스가 더 이상 변경가능하지 않음을 의미한다. (클래스를 값타입 처럼 사용하고 싶을 때 사용한다.)
'프로그래밍 > C#' 카테고리의 다른 글
Rider의 Delegate subtractions warning (0) | 2020.12.16 |
---|---|
C# 9.0이 공개되었습니다. (0) | 2020.05.21 |
[NDC] 이놈의 enum의 박싱을 어찌할꼬 (동영상링크) (0) | 2020.01.05 |
CLR via C# 23장 어셈블리 로딩과 리플렉션 (0) | 2019.12.09 |
CLR via C# 9장 매개변수 (2) | 2019.09.30 |