Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0096 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