Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add read-only property in C#?
A field marked "read-only", can only be set once during the construction of an object. It cannot be changed −
Let us see an example.
class Employee {
readonly int salary;
Employee(int salary) {
this.salary = salary;
}
void UpdateSalary() {
//salary = 50000; // Compile error
}
}
Above, we have set the salary field as read-only.
If you will change it, then a compile-time error will occur. The same is shown in the above example.
Let us now see how to check whether an array is read-only or not −
Example
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());
}
}
}Advertisements