Constant VS Read-Only

Dictionary Meaning:

The meaning of “Constant” is “Something that does not or cannot change or vary.”

What is Constant?

Constants are unchangeable value that do not change for the life of the program. Constants are declared with the const modifier.

constrn

Let’s have a look at Const:

Constants are immutable values which are known at compile time and do not change for the life of the program. Value must be initialized,initialization must be at compile time.

This type of constant is called Compile time Constant.

For example:

namespace ConstReadonly
{
    class Program
    {
        public const int month = 12;
        static void Main(string[] args)
        {
            Console.WriteLine(month);
            Console.ReadKey();
        }
    }
}

Notes:

  1. To assign value to const is must, otherwise it’ll get compilation error (A const field requires a value to be provided)
  2. By default it is static, if we set it static it’ll get compilation error (Cannot be marked static)
  3. Value is hard coded.
  4. Can define constonly on primitive types like int, double, etc.

Let’s have a look at Read-only:

Read-only variables can only being assigned on its declaration and another way is to assign value inside an instance/static constructor.

This type of constant is called Run time Constant.

For example:

namespace ConstReadonly
{
    class Program
    {
        public static readonly int week = 7;
        public const int month = 12;
        static void Main(string[] args)
        {
            Console.WriteLine(week);
            Console.ReadKey();
        }
    }
}

Another example:

namespace ConstReadonly
{
    class ReadOnly
    {
        public readonly int week = 7; // initialized at the time of declaration
        public ReadOnly()
        {
            week = 10;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ReadOnly objRn = new ReadOnly(); // initialized at run time
            Console.WriteLine(objRn.week);
            Console.ReadLine();
        }
    }
}

Notes:

  1. To assign value is not mandatory, but once it is assigned that do not change for the life of the program
  2. They can be static or instance.
  3. Must have set instance value.
  4. Value can assign at run-time. If we set it value directly it’ll get compilation error (A static read-only field cannot be assigned to (except in a static constructor or a variable initializer)

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

Leave a Reply