Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the IsReadOnly property of ArrayList class in C#?
The IsReadOnly property of the ArrayList class in C# returns a boolean value indicating whether the ArrayList is read-only. A read-only ArrayList cannot be modified after creation − you cannot add, remove, or change elements.
Syntax
Following is the syntax for using the IsReadOnly property −
bool isReadOnly = arrayList.IsReadOnly;
Return Value
The IsReadOnly property returns −
true − if the ArrayList is read-only
false − if the ArrayList can be modified
Using IsReadOnly with Regular ArrayList
A regular ArrayList created using the default constructor is always modifiable, so IsReadOnly returns false −
Example
using System;
using System.Collections;
class Demo {
public static void Main() {
ArrayList arrList = new ArrayList();
arrList.Add("Apple");
arrList.Add("Banana");
Console.WriteLine("ArrayList IsReadOnly: " + arrList.IsReadOnly);
Console.WriteLine("Elements: " + arrList.Count);
// Since it's not read-only, we can modify it
arrList.Add("Orange");
Console.WriteLine("After adding Orange: " + arrList.Count);
}
}
The output of the above code is −
ArrayList IsReadOnly: False Elements: 2 After adding Orange: 3
Using IsReadOnly with Read-Only ArrayList
You can create a read-only wrapper around an existing ArrayList using ArrayList.ReadOnly() method −
Example
using System;
using System.Collections;
class Demo {
public static void Main() {
ArrayList originalList = new ArrayList();
originalList.Add("Item1");
originalList.Add("Item2");
// Create a read-only wrapper
ArrayList readOnlyList = ArrayList.ReadOnly(originalList);
Console.WriteLine("Original ArrayList IsReadOnly: " + originalList.IsReadOnly);
Console.WriteLine("Read-only ArrayList IsReadOnly: " + readOnlyList.IsReadOnly);
try {
readOnlyList.Add("Item3"); // This will throw an exception
}
catch (NotSupportedException ex) {
Console.WriteLine("Exception: " + ex.Message);
}
}
}
The output of the above code is −
Original ArrayList IsReadOnly: False Read-only ArrayList IsReadOnly: True Exception: Collection is read-only.
Common Use Cases
The IsReadOnly property is commonly used to −
Validate before modification − Check if the ArrayList can be modified before attempting to add or remove elements
Defensive programming − Ensure your code handles read-only collections properly
API design − Return read-only collections to prevent external modification of internal data
Conclusion
The IsReadOnly property helps determine whether an ArrayList can be modified. Regular ArrayLists return false, while read-only wrappers created using ArrayList.ReadOnly() return true, preventing any modifications to the collection.
