Declare a Read-only Variable With the Const Keyword

Introduction

Whenever I interview any candidate, I always ask one question: what are readonly and constant variable? Believe me, even the near experienced candidates get confused. Therefore, any I learned from my tech gurus most this concept I will effort to explain in detail so beginners and experienced candidates can ameliorate understand.

Let's first with a definition...

What is a Constant variable?

A variable whose value can not be changed during the execution of the programme is called a constant variable.

In the above definition, the value tin non exist changed during execution of the programme, which means nosotros cannot assign values to the constant variable at run time. Instead, information technology must be assigned at the compile time.

Constants are of the post-obit types:

In the in a higher place 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 non be changed during the execution of the program.

Syntax

          int const a=x;        

Some key points most const variable

  • It must exist assigned a value at the fourth dimension of declaration.
                  int const a=ten;            
  • const only allow constant variables into the expression.
                  int const a=10; int const b=20; // right int const c=a+b;   int  d=i; int const c=d+b;   //compile time mistake considering d variable is the non constant into expression.            
  • const tin can be declared at the class level as well as within the method.
  • const can not exist declared using static keyword because they are by default static.
  • constants are absolute constants in which their value cannot be inverse or assigned at the run time.
  • constant variables are compile time variables.

When to use const

The const is used when its value is absolutely constant. Such PI values cannot be changed, but according to your needs, y'all can employ it every bit you wish rather than declaring PI values.

Example ofconst variable.

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

The output of the above programme is thirty. From the above example, nosotros conspicuously see that the const must exist assigned the value at declaration time and in expression both the variables must be const.

Runtime constants (Readonly)

The Run time constants are alleged by using the Readonly keyword which 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'due south non merely to assign a value at the time of proclamation, we tin can also assign the value for read-merely through the constructor
                  int readonly a; a=0;            
  • Readonly allows, readonly constant every bit well every bit non-readonly constant variables into the expression.
                  int readonly a=10;  int b=i; int readonly c=a+b;            
  • Readonly can be alleged just at the course level, not inside the method.
  • Readonly can not be declared using static keywords because they are past default static.
  • Readonly constant'southward value can be set through the reference variable.
  • Readonly constant variables are a runtime time constant variable.

When to use Readonly

Nosotros can use Readonlywhen its value is not an absolute constant, which means information technology can exist changed oft, such as dollars vs INR, in this requirement nosotros tin can set the value through a configuration file or another variable expression and then we can avoid irresolute the grade file often.

Case of Readonly variable.

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

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

Now, let us explain it through this sample program

          using Organization;   using Organization.Configuration;      namespace Usingreadonly {       form Program       {           readonly int a = x;           int b = 30;           int c;           readonly cord r;           public Program()           {               r = ConfigurationManager.AppSettings["DollarPrice"];               Console.WriteLine("The dollar value is:"+" "+r);               Console.WriteLine();               c = a + b;               Console.WriteLine("The improver of readonly constant and non Readonly abiding is :"+Environment.NewLine+ c);               Panel.ReadLine();           }              static void Chief(string[] args)           {               Program p = new Program();                             Panel.ReadLine();           }       }   }        

In the higher up plan ,nosotros have assigned the value for readonly constant through constructor which is divers in the config  file since a readonly abiding 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 announcement merely, while readonly fields can exist initialized at 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 static modifier, while readonly fields can exist used with static modifier.
  4. const field is a compile-fourth dimension constant, the readonly field can be used for run time constants.

Summary

I hope this article is useful for potential interviews. If you take any suggestions regarding this article, then delight contact me.

yancydamitish.blogspot.com

Source: https://www.c-sharpcorner.com/UploadFile/0c1bb2/read-only-and-constant-in-C-Sharp/

0 Response to "Declare a Read-only Variable With the Const Keyword"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel