Home
Search
Array.AsReadOnly MethodUse the Array.AsReadOnly method to get a ReadOnlyCollection from an array.
C#
This page was last reviewed on Mar 26, 2022.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 26, 2022 (simplify).
Home
Changes
© 2007-2023 Sam Allen.