
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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()); } } }
- Related Articles
- How to make Java ArrayList read only?
- How to create a read-only list in Java?
- How to make an ArrayList read only in Java?
- How to make a collection read only in java?
- How to make the Tkinter text widget read only?
- How to make Laravel (Blade) text field read-only?
- How to specify that the element is read-only in HTML?
- How to update only one property in MongoDB?
- Read-only tables in Lua programming
- Change a file attribute to read only in Java
- How to read only 5 last line of the text file in PHP?
- Make a Hashtable read-only in Java
- Create a Read-Only Collection in Java
- Golang program to make a file read-only
- How to return only a single property “_id” in MongoDB?

Advertisements