[c#] const를 쓰면 좋은 점 – static

const로 선언하면 상수가 속한 클래스의 인스턴스를 만들지 않고도 다른 클래스에서 상수를 읽을 수 있다.

public partial class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {
        Text = Form2.TestInt.ToString();
    }
}

public partial class Form2 : Form
{
    public const int TestInt = 1;
}

위 예제에서 Form2의 인스턴스를 만들든 만들지 않든 상수의 값은 바뀌지 않는다. 따라서 그냥 읽을 수 있게 한 거다.

기술적으로 설명하면 상수는 static으로 선언한 셈이다. 그래서 static으로 선언할 수 없다. 이미 선언되어 있기 때문이다.

The static modifier isn’t allowed in a constant declaration.
The const keyword