Read only field
In this chapter you will learn:
Create read only field
A read only field declared with readonly modifier cannot change its value after declaration or outside the constructors.
using System; //from j a va2 s .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 following code has a Rectangle with readonly width and height.
using System;/*from j av a 2s. 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:
Set read only field in constructor
The code above initialize the readonly fields when declaring them. We can also set the value in the contructor.
using System;/*from j a va2 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:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class