Wednesday, May 12, 2021

C# Difference between const and readonly keywords

There are two types of constants in C# constants. A constant in C# can be either a compile-time constant or a run-time constant. The compile time constant is denoted using const symbol and the run-time constant is denoted using readonly symbol. The differences between them are explained below.

CONST KEYWORD
The const keyword is used to declare and define a constant variable which value cannot be changed/re-initialized again in the program. The 'const' constant variable is declared and at the same time its value is defined i.e. initialized. Omitting the initialization will throw compile time exception. For example,

const int MaxScore = 100; is legal but
const int MaxScore; is illegal

Also, we cannot reinitialize a const variable post its declaration. For example, 
const int MaxScore =100;
MaxScore =150; //illegal, re-initialized is not allowed.

Also, const variable cannot be accessed by an object. This fact is illustrated in the example program later. In fact, a const variable is class level variable and hence can be accessed by the class name. So, we can access it using the syntax ClassName.ConstName

Another fact is this that a const variable cannot be provided static modifier. For example, the following declaration is illegal.

static const int MaxScore =100; //illegal

The question arises if a const variable is at class level then why static modifier is not allowed. We can understand this fact after some ponderance. I have tried to explain it below.

First we consider about variable, not constant. Let's take x as variable. Now,

int x ; // each object can access this non-static x as a separate copy
static int x; // each object will access the same memory location of x but the value may not necessarily be constant, it can be altered. All objects will have the altered value. Now, if do not want to alter the value, it means that we want to have static constant value, we use const keyword to denote this concept. Okay, now imagine about the following.

Explanation by contrary hypothesis. Let we can write like static const x =100;

IMAGINE: If we could write like static const x=100; it would imply that there can be const x=100; as well. And const x =100 will be then considered as non-static as static const x =100 will be static. But this cannot be so. By definition, the const variable x is a constant value for all objects and cannot be non-static. Therefore, static keyword is not used with const variable although it is static or class level.

READONLY KEYWORD
The readonly keyword is used to declare a constant variable which value can be initialized in a constructor and cannot be changed/re-initialized again in the program anywhere else. The 'readonly' constant variable can be declared and defined at the same time but it is not mandatory like const variable. The readonly variable is a runtime constant because the value is initialized or reinitialized when the constructor is invoked at runtime. The static modifier can be used with a readonly variable and it can be static or nonstatic but a const variable cannot have static modifier.

readonly x; //valid declaration without initialization is allowed unlike const variable
static readonly x; //valid, static modifier is allowed unlike const variable
static readonly x=100; //valid

When readonly variable is not initialized during declaration as in first and second case, it is initialized inside the constructor. It is readonly constant because it cannot be reinitialized again anywhere else except inside the constructor. 

EXAMPLE PROGRAM

using System;

namespace ConsoleReadOnlyvsConst

{

    class Student

    {

        public string Name { get; set; }

        public Student(string name)

        {

            this.Name = name;

        }

    }

    class Program

    {

        //two types of constant variables:- const and readonly

        //Features of const: 1. declare and define together 2. cannot be static

        //3. cannot be reinitialized 4. not bound with object, Intellisense will not show const variable if we write object followed by dot 5. but className then dot will show const variable in the Intellisense list

        const int scale=1000;

        readonly double roVar; //declared only

        static readonly double PI=3.14;//

        private readonly Student s1 = new Student("Ajeet");

       

        public Program(double d) //non-static constructor

        {

            roVar = d;//Initialized at run time when constructor is invoked

            s1 = new Student("Ram");

        }

 

        static Program() //static constructor

        {

            PI = 3.1415;

        }

 

        static void Main(string[] args)

        {

            Program p = new Program(10.20);

            //scale = 1000; //illegal const scale cannot be re-initialized

            Console.WriteLine(Program.scale); //Classname.ConstVarName

            Console.WriteLine(scale);

            Console.WriteLine(PI);

            Console.WriteLine(p.roVar);

            Console.ReadKey();

        }

        public void Display()

        {

            //s1 = new Student("Krishna"); // illegal

            //roVar = 1.78; // illegal

        }

    }

}

 


No comments:

Post a Comment

Hot Topics