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.
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.
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
What does Array.AsReadOnly
do internally? It calls into the ReadOnlyCollection
constructor. In that constructor, the array is received as an IList
instance.
ReadOnlyCollection
. Little extra memory is used when this method is called.Length
property becomes Count
.We demonstrated Array.AsReadOnly
. We explored the System.Collections.ObjectModel
namespace to see ReadOnlyCollection
. AsReadOnly()
restricts access to arrays by client code.