Readonly and constant variables in C#

Whenever an interviewer took an interview of any candidate, then they always asked one question to them which is read only and constant variable, then believe me, even four-plus experienced candidates get confused, so whatever I learned from my tech gurus about this concept, I will try to explain it in detail so that beginners and experienced candidates can understand it. So let us start with the definition.

What is Constant variable?

The variable whose value cannot be changed during the execution of the program is called a constant variable.

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

Constants are of following types
 

In the above diagram ,we can see the Constants are of two types
  • Compile time constants (const)
  • Runtime constants (Readonly)

Compile time constants

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

Syntax

     int const a=10;

Some key points about const variable
  •   Its must to assign value at the time of declaration.
             eg.
             int const a=10;  
  •   const only allow constant variables into the expression.
   eg.
          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.
  • Constants can be declared at class level as well as inside the method.
  • Constants cannot be declared using the static keyword because they are by default static.
  • Constants are an absolute constant which value can no be changed or assigned at the run time.
  • Constant variable are a compile-time constant variable.

When to use Const?

The const is used when their value is absolute constant, such PI values which cannot be changed, but according to your requirement, you can use it as a wish rather than PI values declaration.

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 clearly see that the const must assign the value at declaration time and in expression both the variable must be const.

Runtime constants (Readonly)

The run time constants are declared by using the Readonly keyword, which value cannot be changed during the execution of the program.

Syntax

int Readonly a; or
int Readonly a=0;

Some key points about const variable

It does not have to assign value at the time of declaration, we can also assign the value for readonly through the constructor.

Example

int readonly a;
a=0;

Readonly allows, readonly constant as well as non readonly constant variables into the expression.

Example

int readonly a=10;
int b=1;
int readonly c=a+b;
  • The Readonly can be declared only at the class level, not inside the method.
  • Readonly cannot be declared using the static keyword because they are by default static.
  • The Readonly constants value can be set through a reference variable.
  • Readonly constant variable is runtime time constant variable.

When to use Readonly?

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

Example of Readonly variable.

Let us define the value from the config file for read-only 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 a 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 readonly constant through a constructor which is defined in the config file because readonly constant does not have to assign the value at the time of declaration.

Now run the program, the output will be as follows

 

Let's outline the differences between const and Readonly variables.
  • The const fields have to be initialized while declaration only, while Readonly fields can be initialized at declaration or in the constructor.
  • The const variables can be declared in methods, while Readonly fields cannot be declared in methods.
  • The const fields can be used with a static modifier, while Readonly fields cannot be used with a static modifier.
  • The 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 interview prospective, if you have any suggestion regarding this article, then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compilemode