Readonly and Constant Variables in C#

Introduction

Whenever I interview any candidate, I always ask this question, "what are readonly and constant variables?" What is the difference between a const and a readonly in C#? Believe me, even the most experienced candidates get confused. In this article, let's learn what const and readonly are in C# and when to use them.

What is a Constant variable ib C#?

A variable whose value can not be changed during the execution of the program is called a constant variable. The cost keyword in C# is used to declare a constant variable. 

In the above definition, the value can not be changed during the execution of the program, which means we cannot assign values to the constant variable at run time. Instead, it must be assigned at the compile time.

There are two types of constants in C#, compile-time constant and runtime constant.

 

In the above diagram, we can see the Constants are of two types

  1. Compile time constants (const)
  2. Runtime constants  (Readonly)

Compile time constants

The compile time constants are declared by using the const keyword, in which the value can not be changed during the execution of the program.

Syntax

int const a=10;

Some key points about const variable

  • It must be assigned a value at the time of declaration.
    int const a=10;
  • const only allows constant variables into the expression.
    int const a=10;
    int const b=20; // correct
    int const c=a+b; 
    
    int  d=1;
    int const c=d+b;   //compile time error because d variable is the non constant into expression.
  • const can be declared at the class level and inside the method.
  • const can not be declared using static keywords because they are, by default, static.
  • constants are absolute constants whose values cannot be changed or assigned at the run time.
  • constant variables are compile-time variables.

When to use const

The const is used when its value is constant. Such PI values cannot be changed, but according to your needs, you can use them as you wish rather than declaring PI values.

Example of const variable.

using System;  
  
namespace UsingConst  
{  
    class Program  
    {  
        const int a = 10;  
           
       static void Main(string[] args)  
        {  
            const int b = 20;  
            const int c = b + a;  
            Console.WriteLine(c);  
            Console.ReadLine();  
        }  
    }  
} 

The output of the above program is 30. From the above example, we see that the const must be assigned the value at declaration time, and in expression, both the variables must be const.

Runtime constants (Readonly)

The Run time constants are declared by using the Readonly keyword, whose value can not be changed during the execution of the program.

int Readonly a; or
int Readonly a=0;

Some key points about const variable

  • It's not just to assign a value at the time of declaration. We can also assign the value for read-only through the constructor
    int readonly a;
    a=0;
  • Readonly allows readonly constant and non read-only constant variables into the expression.
    int readonly a=10;
    
    int b=1;
    int readonly c=a+b;
  • Readonly can be declared only at the class level, not inside the method.
  • Readonly can not be declared using static keywords because they are, by default, static.
  • Readonly constant's value can be set through the reference variable.
  • Readonly constant variables are runtime time constant variables.

When to use Readonly

We can use Readonly when its value is not an absolute constant, which means it can be changed frequently, such as dollars vs INR. In this requirement, we can set the value through a configuration file or another variable expression to avoid changing the class file frequently.

Example of Readonly variable

Let's define the value from the config file for a readonly constant variable, which will be set through the constructor. 

<configuration>  
  <appSettings>   
    <add key="DollarPrice" value="61.23"/>  
  </appSettings>
</configuration>

Now, let us explain it through this sample program 

using System;  
using System.Configuration;  
  
namespace Usingreadonly
{  
    class Program  
    {  
        readonly int a = 10;  
        int b = 30;  
        int c;  
        readonly string r;  
        public Program()  
        {  
            r = ConfigurationManager.AppSettings["DollarPrice"];  
            Console.WriteLine("The dollar value is:"+" "+r);  
            Console.WriteLine();  
            c = a + b;  
            Console.WriteLine("The addition of readonly constant and non Readonly constant is :"+Environment.NewLine+ c);  
            Console.ReadLine();  
        }  
  
        static void Main(string[] args)  
        {  
            Program p = new Program();  
             
            Console.ReadLine();  
        }  
    }  
}

In the above program, we have assigned the value for the readonly constant through the constructor defined in the config file since a readonly constant isn't necessary to assign the value at the time of declaration.

Now run the program. The output will be:

Let us outline the differences between const and readonly variables.

  1. const fields need to be initialized with declaration only, while readonly fields can be initialized at the declaration or in the constructor.
  2. const variables can be declared in methods, while readonly fields cannot be declared in methods.
  3. const fields cannot be used with a static modifier, while readonly fields can be used with a static modifier.
  4. const field is a compile-time constant. The readonly field can be used for run-time constants.

Summary

I hope this article is useful for potential interviews. If you have any suggestions regarding this article, then don't hesitate to get in touch with me.


Recommended Free Ebook
Similar Articles