Read only field

A read only field is declared with readonly modifier.

A read only field cannot change its value after declaration or outside the constructors.


using System;
class Rectangle{
   public readonly int Width = 3;
   public readonly int Height = 4;
}
class Program
{
    
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();

        Console.WriteLine(r.Width);

    }
}

The output:


3

The code above initialize the readonly fields when declaring them.

We can also set the value in the contructor.


using System;
class Rectangle {
   public readonly int Width;
   public readonly int Height;
   
   public Rectangle(){
       Width = 5;
       
   }

}

class Program
{
    
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();

        Console.WriteLine(r.Width);
    }
}

The output:


5
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.