[c#] 뮤터블과 이뮤터블의 데이터 불변성 보장

C#에서 데이터 불변성(Immutability)은 매우 중요한 개념이다. 불변성은 어플리케이션의 안정성과 예측성을 높이며, 다중 스레드 환경에서도 문제를 예방할 수 있다.

뮤터블(Mutable) vs 이뮤터블(Immutable)

데이터 불변성 보장 방법

이뮤터블한 클래스를 작성하기 위해 다음과 같은 방법들을 고려할 수 있다:

1. 필드를 읽기 전용으로 선언

public class ImmutableClass
{
    private readonly int _readOnlyField;

    public ImmutableClass(int value)
    {
        _readOnlyField = value;
    }

    public int ReadOnlyField => _readOnlyField;
}

2. 읽기 전용 컬렉션 사용

IEnumerable<string> readOnlyCollection = new List<string> { "apple", "banana", "cherry" }.AsReadOnly();

3. 수정이 불가능한 자료구조 사용

ImmutableStack<int> immutableStack = ImmutableStack<int>.Empty.Push(1).Push(2).Push(3);

4. 값 형식 활용

public struct ImmutableStruct
{
    public int Value { get; }

    public ImmutableStruct(int value)
    {
        Value = value;
    }
}

위와 같은 방법을 사용하여 데이터를 보호하고 불변성을 유지함으로써 예기치 않은 문제를 방지할 수 있다.


위 내용은 Microsoft Docs - Immutability in C#를 참고하여 작성되었습니다.