Difference between Constant and ReadOnly in C#.

Program :-

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;


namespace Test_Application
{
    class Program
    {
        public const int reads = 2;
        private readonly int b = 7;

        public Program()
        {        
            b = 8;  //  value changed while initialization. in run time value will take 8 but not 7.
        }
        static void Main(string[] args)
        {

            Program p = new Program();
         
            Console.WriteLine(reads+" " + p.b);
            Console.ReadLine();
        }
    }
}

Output : 2 8

Constant values remain fixed through out the program.
ReadOnly deside at runtime that value to execute. 

Share this

Previous
Next Post »