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());
      }
   }
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements