Difference between Const and Readonly

Beta 2 compliant 

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

Up Next
    Ebook Download
    View all
    Learn
    View all