Trường readonly chỉ gán một lần trong constructor. Không thể thay đổi.
Ví dụ
class Employee {
readonly int salary;
Employee(int salary) { this.salary = salary; }
void UpdateSalary() { /* salary = 50000; // Lỗi compile */ }
}
Kiểm tra mảng có read-only không:
Ví dụ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lower {
class Program {
static void Main(string[] args) {
Array arr = Array.CreateInstance(typeof(String), 3);
arr.SetValue("Maths", 0);
arr.SetValue("Science", 1);
arr.SetValue("PHP", 2);
Console.WriteLine("isReadOnly: {0}", arr.IsReadOnly.ToString());
}
}
}