Difference between Const and Readonly

Introduction

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;

// Define a class A with a constant integer X
public class A
{
    public const int X = 123;
}

// Compile class A into a library named A.dll
// Usage: csc /t:library /out:A.dll A.cs
// ---------------------------------------------

using System;

// Define a class MyTest with a Main method
public class MyTest
{
    public static void Main()
    {
        // Print the value of the constant X from class A
        Console.WriteLine("X value = {0}", A.X);
    }
}

// Compile class MyTest and link it with the A.dll library
// Usage: csc /r:A.dll MyTest.cs
// ---------------------------------------------

// To run the program, execute "mytest"

// The output should be: 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.

Step 1. Compile A (after making the changes).

csc /t:library /out:A.dll A.cs

Step 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;

// Define a class A with a static readonly integer X
public class A
{
    public static readonly int X = 123;
}

// Compile class A into a library named A.dll
// Usage: csc /t:library /out:A.dll A.cs
// ---------------------------------------------

using System;

// Define a class MyTest with a Main method
public class MyTest
{
    public static void Main()
    {
        // Print the value of the static readonly X from class A
        Console.WriteLine("X value = {0}", A.X);
    }
}

// Compile class MyTest and link it with the A.dll library
// Usage: csc /r:A.dll MyTest.cs
// ---------------------------------------------

// To run the program, execute "mytest"

// The output should be: X value = 123

Now you realised, you have made a mistake. All you need to do is.

Step 1. Recompile A.cs (after making changes)

csc /t:library /out:A.dll A.cs

Step 2. Copy the new dll to the client computer and it should run perfectly. There is no need to recompile your application MyTest.cs

Best wishes and good luck !


Similar Articles