Favicon

Readonly modifier

Peponi11/13/20242m

C#
SyntaxKeywordModifier

1. Introduction

readonlyconst와 비슷한 면이 있는 런타임 형식으로 읽기 전용 멤버를 의미한다. readonly에 할당되는 값은 멤버 선언 또는 생성자 내에서만 가능하며 인스턴스마다 다른 값을 가질 수 있다. 참조 형식 멤버의 경우 참조 인스턴스에 대한 불변성만 보장되며 상태는 변경될 수 있다.

2. Example

Readonly example
public class Point
{
    public readonly int X = 0;
 
    public Point(int x) => X = x;
 
    public void ChangePoint(int x) => X = x;  // CS0191: 읽기 전용 필드에는 할당할 수 없습니다.
}
Reference type example
public class Point
{
    public int X = 0;
 
    public Point(int x) => X = x;
 
    public void ChangePoint(int x) => X = x;
}
 
public class PointTest
{
    readonly Point Point = new Point(1);
 
    public PointTest()
    {
        Console.WriteLine(Point.X);     // 1
 
        Point.ChangePoint(2);
 
        Console.WriteLine(Point.X);     // 2
    }
}

3. 참조 자료