본문 바로가기

프로그래밍/C#

Welcome to C# 9.0 - Init-only properties & record

https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/

 

Welcome to C# 9.0 | .NET Blog

C# 9.0 is taking shape, and I’d like to share our thinking on some of the major features we’re adding to this next version of the language. With every new version of C# we strive for greater clarity and simplicity in common coding scenarios,

devblogs.microsoft.com

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로 선언했다는 뜻이다. 이는 생성 이후 이 클래스가 더 이상 변경가능하지 않음을 의미한다. (클래스를 값타입 처럼 사용하고 싶을 때 사용한다.)