Translate

Sunday, July 28, 2013

C# difference between read only and constant

You might already know that the difference between readonly and constant is that readonly variables can be set in the constructor where as constants once declared cannot be changed.

But that is not the answer that you would expect from a technical person, the difference you read above is just a symptom. The real technical difference between constant and read only is that, the compiler replaces any reference to the constant by its actual value.

For example suppose I have a class Test that references another class Class1. If I am reading a contant value from class Class1 in class Test, then in the assembly of class Test, that reference will be replaced by its actual value.

This is the code for Class 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
    public class Class1
    {
        public const Decimal c = 25;
        public static readonly Decimal d = 40;

    }

}


This is the code for Test

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using ClassLibrary1;

namespace ConstReadOnlyDifference
{
    class Test
    {
       
        static void Main()
        {
            Console.WriteLine(Class1.c);
            Console.WriteLine(Class1.d);

        }
    }
}



Class 1 and Test are in seprate projects.




































If you compile the solution, equivalent of this is what actually goes into the assembly for ConsoleApplication3.


using ClassLibrary1;
using System;

namespace ConstReadOnlyDifference
{
  internal class Test
  {
    private static void Main()
    {
      Console.WriteLine(new Decimal(25));
      Console.WriteLine(Class1.d);
    }
  }
}


As you can see Class1.c is replaced by new Decimal(25)  Which means if you ever change the value of c in Class1, Class Test will still hold its previous value unless class Test is itself recompiled.


So never use constant for a value that will ever change in the future. 

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator