Wednesday, December 2, 2009

Const vs ReadOnly in .net

Const
  • It is also called as "Compile time constant"
  • Const can be assigned at variable initialization
  • Once assigned value cannot be changed
ReadOnly
  • "Runtime constant"
  • ReadOnly field can be assigned at variable initialization and in constructor
  • Value can be changed in constuctor

Sample

    class ReadonlyConstant
    {
        private const int x=10;     //compile time constant
        private readonly int y=20;  //runtime constant

        public ReadonlyConstant()
        {
            Console.WriteLine("\n***Const Vs ReadOnly***");
            Console.WriteLine("Const x before initialization=" + x);
            Console.WriteLine("ReadOnly y before initialization=" + y);



            //The left-hand side of an assignment must be a variable, property or indexer
            //x = 20;   // value cannot be changed in constructor

            y = 110;    // value can be changed in constructor   

            Console.WriteLine("Const x after initialization=" + x);
            Console.WriteLine("ReadOnly y after initialization=" + y);
        }

        //public int IncrementY
        //{
        //    //A readonly field cannot be assigned to (except in a constructor or a variable initializer)
        //     set { y++; }
        //}
    }

    No comments: