Difference between Constant and ReadOnly in C#


Difference between Constant and ReadOnly in C#

1. Constant and ReadOnly both have similar function.
2. Constant assigned in Compile time and  regarding ReadOnly  we can change the value during           initialize time rather than declaretion. please kindly follow the code.


Program:-

using System;
namespace Tests1014
{
   public class Program
    {
        public const int _cons =10 ;
        public  readonly int _readonly = 7;  // declaretion time
        public Program()
        {
            //  _cons = 8;    variable showing red mark because it is assigned in compiletime
            _readonly = 9;      // readonly runtime      "initialize time"

        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("a ="+_cons); // no need of creating object because it is static
            Console.WriteLine("b =" +p._readonly);
            Console.ReadLine(); 
        }
    }
}

Output

a=10
b=9;    run time it value of b change  7 to 9. 

Share this

Previous
Next Post »