HaPpY hApPy

2. const 보다는 readonly가 좋다 본문

.NET/Effective C#

2. const 보다는 readonly가 좋다

juniguya 2013. 8. 17. 12:33

1. 상수형으로 컴파일 타임 상수(const)와, 런타임 상수(readonly) 두가지의 차이점

(빠르지만 가끔 위험한 프로그램),    (가끔 느리지만 안전한 프로그램) 당연히 우린 후자를 선택해야한다!


2. 컴파일 타임 상수는 기본적인 내장자료형이나 enum string에 대해서만 사용가능 하지만 내장 자료형이 아닌

DateTime 을 new 연산자로 초기화 하려 시도하면 컴파일시에 오류가 발생한다.

// Does not compile, use readonly instead:

private const DateTime classCreation = new

DateTime(2000, 1, 1, 0, 0, 0);


3. 또하나 큰 차이점 특정 프로그램에 const를 사용해서 컴파일 해서 배포한 후에

나중에 다시 그 값이 변경되서 배포할때 모두 다 컴파일해서 다시 배포해야되지만 readonly 를 사용하면

그렇게 하지 않아도된다.

public class UsefulValues

{

public static readonly int StartValue = 5;

public const int EndValue = 10;

}


In another assembly, you reference these values:

for (int i = UsefulValues.StartValue; i < UsefulValues.EndValue; i++)

Console.WriteLine("value is {0}", i);


If you run your little test, you see the following obvious output:

Value is 5

Value is 6

...

Value is 9


Time passes, and you release a new version of the Infrastructure assembly

with the following changes:

public class UsefulValues

{

public static readonly int StartValue = 105;

public const int EndValue = 120;

}


you get no output at all. The loop now uses the value 105 for its

start and 10 for its end condition. The C# compiler placed the const value

of 10 into the Application assembly instead of a reference to the storage

used by EndValue. Contrast that with the StartValue value. It was declared

as readonly: It gets resolved at runtime


영어 부분 꼼꼼히 읽어보면 쉽게 이해가 될다 ;)


4. 마지막으로 배포할때 버전을 정의할때

현재 버전만은 꼭 readonly 를 사용하는것이 좋다.

private const int Version1_0 = 0x0100;

private const int Version1_1 = 0x0101;

private const int Version1_2 = 0x0102;

// major release:

private const int Version2_0 = 0x0200;

// check for the current version:

private static readonly int CurrentVersion = Version2_0;

protected MyType(SerializationInfo info,

StreamingContext cntxt)

{

int storedVersion = info.GetInt32("VERSION");

switch (storedVersion)

{

case Version2_0:

readVersion2(info, cntxt);

break;

case Version1_1:

readVersion1Dot1(info, cntxt);

break;

// etc.

}

}