Home
C#
Array.AsReadOnly Method
Updated Mar 26, 2022
Dot Net Perls
Array.AsReadOnly. In the C# language an array itself cannot be read-only. This is not possible with basic array types. For an immutable collection, we need to call a method like AsReadOnly.
Array
With the ReadOnlyCollection and the AsReadOnly method, we add another layer of indirection to eliminate unwanted writes. This gives us an immutable collection—a ReadOnlyCollection instance.
ReadOnlyCollection
Example. Here 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.
int Array
Finally We display the Count. If you try to change an element in the ReadOnlyCollection, your program won't compile.
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++) { Console.WriteLine(result[i]); } } }
Count: 3 1 5 3
Internals. What does Array.AsReadOnly do internally? It calls into the ReadOnlyCollection constructor. In that constructor, the array is received as an IList instance.
Constructor
Then A reference to the original array is stored as a field in ReadOnlyCollection. Little extra memory is used when this method is called.
IList
Warning This extra level of indirection has a performance cost. And it introduces a name change: the Length property becomes Count.
A summary. We demonstrated Array.AsReadOnly. We explored the System.Collections.ObjectModel namespace to see ReadOnlyCollection. AsReadOnly() restricts access to arrays by client code.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 26, 2022 (simplify).
Home
Changes
© 2007-2025 Sam Allen