방프리

21.10.26 Chapter1. 데이터 타입 (Item 3) 본문

C#/More Effective C#

21.10.26 Chapter1. 데이터 타입 (Item 3)

방프리 2021. 10. 27. 00:11

Item 3 : 값 타입은 변경 불가능한 것이 낫다.

 

코딩을 하다보면 값이 변경되지 않아야 하는 것들이 있을 수 있다.

예로 아이템의 기본정보라던지, 특정 AccessKey값 등 여러 종류가 있겠다.

이들을 어떻게 만들면 될까? 간단한 방법으로는 const를 떠올릴 수도 있겠지만 좀 더 C#의 기능을 사용해서 

변경하는 방법도 있다.

public struct Address
{
    public string Line1 { get; }
    public string Line2 { get; }
    public string City { get; }
    public string State { get; }
    public int ZipCode { get; }
    
    public Address(string _Line1, string _Line2, string _City, 
                     string _State, int _ZipCode)
    {
        this.Line1 = _Line1;
        this.Line2 = _Line2;
        this.City = _City;
        this.State = _State;
        this.ZipCode = _ZipCode;
    }
}

get 속성만 주어서 생성자에서 값을 준 후에 변경하지 못하게 하는 방법이 있을 수 있고

public struct PhoneList
{
    private readonly ImmutableList<Phone> phones;
    
    public PhoneList(Phone[] ph)
    {
        phones = ph.ToImmutableList();
    }
    
    public IEnumerable<Phone> Phones => phones;
}

Immutable 속성을 적극 활용하여 변경을 막는 방법도 있다. 

Immutable 속성 뿐만 아니라 ReadonlyCollection 타입도 있으니 참고하면 매우 좋다.

 

Comments