www.c-sharpcorner.com 사이트에서 다음의 글을 보았습니다
http://www.c-sharpcorner.com/UploadFile/sayginteh/ConstAndReadOnly11112005005151AM/ConstAndReadOnly.aspx
상수를 선언시 const 와 readonly 를 사용했을 때의 차이점과 애로사항(?)을 알려 주네요...
그러나, 이 글에서는 왜 이렇게 차이가 나는지에 대한 근본적인 원인에 대해서는 언급하지 않고 있네요
(언급할 필요를 못 느꼈나요 ^^; 뭐.. 이유야 어떻든, 그 원인에 대해 끄적여 봅니다)
-----------------------------------------------------------------------------------------------------------------------------
왔다 갔다, 귀찮으니깐 원본 글 가져와 봅니다
This source code below is an an example of the difference between const and readonly. Say you created a file A.cs and then compiled it to A.dll. Then you write your main application called MyTest.cs. After compiling MyTest.cs with referencing A.dll, you run the MyTest.exe.
using System;
public class A
{
public const int X = 123;
}
csc /t:library /out:A.dll A.cs
using System;
public class MyTest
{
public static void Main()
{
Console.WriteLine("X value = {0}", A.X);
}
}
csc /r:A.dll MyTest.cs
To run: mytest
The output :
X value = 123
Then you install the program into your client computer. It runs perfectly.
One week later, you realised that the value of X should have been 812 instead of 123.
What you will need to do is to
1] Compile A (after making the changes)
csc /t:library /out:A.dll A.cs
2] Compile your application again
csc /r:A.dll MyTest.cs
This can be a little troublesome. However, if you used the readonly instead of const,the situation will be slightly different. You start with
using System;
public class A
{
public static readonly int X = 123;
}
csc /t:library /out:A.dll A.cs
using System;
public class MyTest
{
public static void Main()
{
Console.WriteLine("X value = {0}", A.X);
}
}
csc /r:A.dll MyTest.cs
To run: mytest
The output :
X value = 123
Now you realised, you have made a mistake. All you need to do is
1] Recompile A.cs (after making changes)
csc /t:library /out:A.dll A.cs
2] Copy the new dll to the client computer and it should run perfectly. There is no need to recompile your application MyTest.cs here
Best wishes and good luck !
saygin
-----------------------------------------------------------------------------------------------------------------------------
외부 라이브러리에서 상수를 선언하고 이를 참조하여 어플리케이션에서 사용하는 시나리오 입니다
이때 외부 라이브러리의 상수 값이 변경되어 이 라이브러리를 재 컴파일하여 DLL을 재배포 할 경우,
값의 변경이 있느냐 없느냐 하는 문제네요...
결론적으로 const로 선언된 상수는 외부 라이브러리만 재컴파일 해서는 안되고
이를 사용하는 어플리케이션도 같이 재 컴파일 되어야 원하는 대로 변경이 적용됨을 알 수 있슴다
그럼, readonly는 되고 const는 왜 안될까요? 원인에 대해 알아 봅니다
const 로 상수를 선언하면 컴파일 시 결정된 값에서 더 이상 변경되지 않기 때문에 닷넷 컴파일러는
IL 코드 생성시 이 값을 어플리케이션의 일부로 포함시켜 버립니다
아래는 const 로 선언한 경우 어플리케이션의 IL 코드입니다
IL코드에서 보는 바와 같이, 123이라는 상수 값이 외부 라이브러리가 아닌,
이를 참조해서 사용하는 어플리케이션 일부로 포함된 것을 알 수 있습니다

반면, readonly 로 선언된 경우는 다음과 같습니다
const는 필드를 선언할 때 만 값을 초기화 할 수 있는 반면,
readonly는 선언시, 그리고 생성자에서 한번 더 값을 초기화 할 수 있는 특징이 있습니다
아래 IL 코드를 보면,
const 와는 달리 외부 라이브러리(Classlibrary1)의 참조가 IL코드에 정의되어 있습니다
따라서 라이브러리만 재 배포 하여도 변경 값이 적용되는 것이죠
('const 는 컴파일 상수, readonly 는 런타임 상수로 사용할 수 있다' 라는 msdn의 말이 다시금 와 닿지 않는가..)
