C# readonly 필드와 get 프로퍼티의 차이

Pilgyeong_G·2024년 1월 4일
0
public class Class1
{
	public readonly int Field1;
    public int Property1 { get; }
}

위 클래스의 Field1Property1은 외부에서 읽기 전용이라는 점에서 같다.

그러면 외부에 공개해야되는 값은 Field1 처럼 선언하는게 더 나아보이겠지만 Property1처럼 프로퍼티로 읽기 전용 값을 선언해야되는 경우도 있다.

바로 인터페이스를 사용할 때인데, C#의 인터페이스는 메소드, 프로퍼티만 선언할 수 있고 변수는 선언할 수 없다.

public interface IClass1
{
	public int Property1 { get; }
}

public class Class1 : IClass1
{
	public readonly int Field1;
    public int Property1 { get; }
    
    public Class1()
    {
    	Field1 = 1;
        Property1 = 2;
    }
}

...

public void PrintNumber(IClass1 c)
{
	Console.WriteLine(c.Property1); // 가능
    Console.WriteLine(c.Field1); // 불가능
}

위와 같이 인터페이스를 선언했을 때, 인터페이스로 인스턴스에 접근할 때 읽기 전용으로 제한하여 캡슐화를 유지할 수 있다.

0개의 댓글