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.
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.
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.
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.
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).