Constant VS ReadOnly In C#

Introduction

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.

constant

Let’s have a look at Const

Constants are immutable values that are known at compile time and do not change for the life of the program. The value must be initialized; initialization must be at compile time.

This type of constant is called Compile time Constant.

Example

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

Note

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

Let’s have a look at Read-only

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

This type of constant is called the Run time Constant.

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();
        }
    }
}

 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();
        }
    }
}

Note

  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 instant.
  3. Must have set instance value.
  4. Value can be assigned at run-time. If we set the value directly, it'll get a compilation error. A static read-only field cannot be assigned to (except in a static constructor or a variable initializer).


Similar Articles