C# Array.AsReadOnly

Array type

An array itself cannot be read-only. This is not possible with basic array types. But with the ReadOnlyCollection and the AsReadOnly method on the Array class, we add another layer of indirection to eliminate unwanted writes.

This C# array article demonstrates the Array.AsReadOnly method.

Example

Note

Let's get started by looking at this simple program. Please notice that the System.Collections.ObjectModel namespace is included; this is because the ReadOnlyCollection is found there. We call Array.AsReadOnly and pass the int[] array as the argument. Finally, we display the Count property of the ReadOnlyCollection. If you try to change an element in the ReadOnlyCollection, your program won't compile.

Program that uses Array.AsReadOnly [C#]

using System;
using System.Collections.ObjectModel;

class Program
{
    static void Main()
    {
	int[] array = { 1, 5, 3 };
	ReadOnlyCollection<int> result = Array.AsReadOnly(array);

	Console.WriteLine("Count: " + result.Count);
	for (int i = 0; i < result.Count; i++)
	{
	    // Can't touch this.
	    Console.WriteLine(result[i]);
	}
    }
}

Output

Count: 3
1
5
3

Implementation

.NET Framework information

What does Array.AsReadOnly do internally? Does it copy the array? In my investigation, I found that AsReadOnly simply called into the ReadOnlyCollection constructor. In that constructor, the array is received as an IList instance. A reference to the original array is stored as a field in ReadOnlyCollection. So very little extra memory is used when this method is called.

IList Generic Interface

Summary

The C# programming language

We demonstrated Array.AsReadOnly and also ventured into the System.Collections.ObjectModel namespace to see the ReadOnlyCollection type. Arrays cannot be made immutable in the C# language; elements can always be assigned. Thus, Array.AsReadOnly makes it possible to restrict access to arrays by client code. This extra level of indirection will have some performance cost and also introduces a change in nomenclature: the Length property becomes Count, for example.

Array Types
.NET