One difference is that
A
constant
value will be embedded in the
executable
file at compile time, and substitutes it at all places wherever it is used. So, if the
constant
value is changed in the library, which is referenced by your application, then your application also requires to be re-compiled.
A
read only
variable is read by the program at run time. So, if the value of the read only variable is changed in the library, which is referenced by your application, without recompiling your application, the new value of the
read only
variable will be read by the program.
[edit]An example added to elaborate the above points[/edit]
using System;
namespace ConstReadOnlyTest {
class Program {
static void Main(string[] args) {
Console.WriteLine("Value of Constant from Library: {0}", SupportingLib.Class1.ConstString);
Console.WriteLine("Value of Read ony variable from Library: {0}",SupportingLib.Class1.ReadOnlyString);
Console.ReadKey();
}
}
}
using System;
namespace SupportingLib {
public class Class1 {
public const string ConstString = "Constant";
public static readonly string ReadOnlyString = "Readonly";
}
}
When I compile this code and run it the output is
Value of Constant from Library: Constant
Value of Read ony variable from Library: Readonly
My application is shipped. Later, a change is made in the referenced library
and Company A supplied me new compiled library with same version 1.0.0.0
This is the changed code in the referenced library
public const string ConstString = "Constant Changed";
public static readonly string ReadOnlyString = "Readonly Changed";
Without recompiling my application I have only supplied the new compiled version of the referenced library to the user. Then the output is
Value of Constant from Library: Constant
Value of Read ony variable from Library: Readonly Changed
The reason being when I compiled my application the string "Constant" was copied from the referenced assembly and placed in my executable code. Whereas, for Read only variable the program reads from the referenced assembly at run time.
So, when I supplied new compiled library the program did read the read only variable from the new compiled referenced library. Hence in the second line of output we got: "Readonly Changed"
Whereas the program used the constant from within my application so the value "Constant" is printed in the first line.
Hope I clarified what I thought.