Readonly fields

Readonly fields behave like constants with one difference. A readonly field can be initialized on declaration, or can be initialized only once in a constructor, and no where else.

In the following example, a readonly field is initialized:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;


namespace ConsoleApplication6
{   
    class Program
    {
        readonly int num;

        public Program()
        {
            this.num = 10;
        }

        public void TestIt()
        {
          // The below line is error
          //  this.num = 40;
        }
         
        static void Main(string[] args)
        {

            Program p = new Program();
            Console.WriteLine(p.num);
        }        
        
    }
}

 

 

Add a Comment

Your email address will not be published. Required fields are marked *