How to mark a field as read only in C#
Create read only field
A read only field declared with readonly modifier cannot change its value after declaration or outside the constructors.
using System; // w w w. j a v a2s . c o m
class MainClass {
public static readonly int SIZE = 10;
public static void Main() {
int[] nums = new int[MainClass.SIZE];
// MainClass.SIZE = 100; // Error!!! can't change
}
}
The code above generates the following result.
Example
The following code has a Rectangle with readonly width and height.
using System;/*from w ww . jav a2 s . c o m*/
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:
Example 2
The code above initialize the readonly fields when declaring them. We can also set the value in the contructor.
using System;//w ww . j a v a 2 s . c o m
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: