In C#, Array.AsReadOnly<T>(array) returns a ReadOnlyCollection<T> that wraps your array. Callers can read and enumerate, but cannot add, remove, or set items through that collection.
It does not copy the elements. If you still hold the original T[], changes to the array are visible through the wrapper. For a true snapshot, copy first, then wrap.
This is a static member of System.Array. You call it with the class name, such as Array.AsReadOnly(...). Arrays in C# have a fixed length after creation; use List<T> when the count must grow.
Syntax
Pass the array to the static method and keep the read-only collection.
C#
var view = Array.AsReadOnly(nums);
Console.WriteLine(view[0]);
Call
What it does
Array.AsReadOnly(nums)
Returns a read-only view over nums.
view.Count
Same as the array Length.
Needs using System.Collections.ObjectModel; only if you name the type explicitly; var is enough in many samples.
Library declarations
C#
public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array);
Parameters
Parameter
Description
array
Required. The source T[] to wrap. Do not pass null.
Return Value
Return Value
Description
ReadOnlyCollection<T>
A wrapper that exposes read access. Mutations through the collection throw.
C# Examples
Example 1 — Wrap and Read
Create a read-only view and print items by index.
C#
using System;
using System.Collections.ObjectModel;
class Program {
static void Main() {
string[] names = { "Ann", "Bob", "Cara" };
ReadOnlyCollection<string> view = Array.AsReadOnly(names);
Console.WriteLine("Count: " + view.Count);
Console.WriteLine("view[1] = " + view[1]);
foreach (string n in view) {
Console.Write(n + " ");
}
Console.WriteLine();
}
}
Output
Count: 3
view[1] = Bob
Ann Bob Cara
How It Works
Wrap.AsReadOnly returns a collection facade over the same storage.
Count mirrors Length. Three names means Count is 3.
Index read works.view[1] returns Bob.
foreach works. Enumeration is allowed; mutating APIs are not.
Example 2 — Writes Through the View Throw
Trying to assign via the read-only collection fails at runtime.
C#
using System;
using System.Collections.ObjectModel;
class Program {
static void Main() {
int[] nums = { 1, 2, 3 };
ReadOnlyCollection<int> view = Array.AsReadOnly(nums);
try {
// IList indexer set is not supported
((System.Collections.Generic.IList<int>)view)[0] = 9;
} catch (NotSupportedException) {
Console.WriteLine("Write blocked");
}
Console.WriteLine("nums[0] still " + nums[0]);
}
}
Output
Write blocked
nums[0] still 1
How It Works
Read-only contract. The collection rejects set operations.