Here is a quick overview on the differences between 'const' and 'readonly' in C# and ASP.net
const: Cannot be static, and it is evaluated at compile time. It can also only be initiailized at declaration.
Example:
1: public class ConstTest
2: {
3: class SampleClass
4: {
5: public int x;
6: public int y;
7: public const int c1 = 5;
8: public const int c2 = c1 + 5;
9:
10: public SampleClass(int p1, int p2)
11: {
12: x = p1;
13: y = p2;
14: }
15: }
16:
17: static void Main()
18: {
19: SampleClass mC = new SampleClass(11, 22);
20: Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
21: Console.WriteLine("c1 = {0}, c2 = {1}",
22: SampleClass.c1, SampleClass.c2 );
23: }
24: }
25: /* Output
26: x = 11, y = 22
27: c1 = 5, c2 = 10
28: */
readonly: Can be either instance-level or static. The value is evaluated at run time. It can be initialized in declaration or by code in the constructor.
Example:
1: public class ReadOnlyTest
2: {
3: class SampleClass
4: {
5: public int x;
6: // Initialize a readonly field
7: public readonly int y = 25;
8: public readonly int z;
9:
10: public SampleClass()
11: {
12: // Initialize a readonly instance field
13: z = 24;
14: }
15:
16: public SampleClass(int p1, int p2, int p3)
17: {
18: x = p1;
19: y = p2;
20: z = p3;
21: }
22: }
23:
24: static void Main()
25: {
26: SampleClass p1 = new SampleClass(11, 21, 32); // OK
27: Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
28: SampleClass p2 = new SampleClass();
29: p2.x = 55; // OK
30: Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
31: }
32: }
33: /*
34: Output:
35: p1: x=11, y=21, z=32
36: p2: x=55, y=25, z=24
37: */
In summary, the distinguishing factor between the two modifiers in C# is that const items are dealt with at compile-time, while the values of readonly fields are specified at run time. This means that assignment to readonly fields may occur in the class constructor as well as in the declaration.