Constant Vs ReadOnly in C#

 


# const vs readonly in c#


Constant:- The Constant refer to fix values that the program may not alter during its execution.These fixed values are also called literals.

  

 Example:-

    class Program

    {

       const double pi = 3.14159;    // Can be Used as field 

        const double pi;              // Error- Initialization must, outherwise compilation error occur


         public void Print()

        {

            const double pi = 3.14159;  //:- Can be Used as a local variable  

            Console.WriteLine("value of PI: " + pi);

        } 

        static void Main(string[] args)

        {

            Program obj = new Program();

            obj.Print();

        }

    }


Types of Constant

  • Integer Constant
  • Float Constant
  • Character Constant
  • String Constant
  • Enumeration Constant

 

Note:- Hence it is necessary that you assign a value to a constant variable/fields at the time of its declaration.The const keywords can be used before a fields and a local variable.The const field values will be evaluated during the compile time in c#.


ReadOnly:- Read-only fields in c# can be created by using readonly keyword. In c#, the readonly fields can be initialized either at the time of declaration or in a constructor. The readonly field values will be evaluated during the run time in c#.

 Example 1:-

 

   class Program
 
    {
 
        readonly string first_Name = "John";
        readonly string last_Name; //Initialization is not neccessary
 
        public void Print()
 
        {
            readonly string first_Name = "John";  // Can not be used as a local variable
 
            Console.WriteLine("Value of Name:" + first_Name);
 
        }
 
        static void Main(string[] args)
 
        {
 
            Program obj = new Program();
 
            obj.Print();
 
        }
 
    }


 Example 1:- Initialize using readonly using constructor


    class Age

    {

        private readonly int _year;

        Age(int year)

        {

            _year = year;

        }

   

        public static void Main()

        {

            Age obj = new Age(2022);

            Console.WriteLine("Age=" +obj._year);

        }

    }


We can assign a value to a readonly field only in the following contexts:-


  • When the variable is initialized in the declaration.

  • In an instance constructor of the class that contains the instance field declaration.

  • In the static constructor of the class that contains the static field declaration.

No comments:

Post a Comment