C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Finally: We display the Count. If you try to change an element in the ReadOnlyCollection, your program won't compile.
C# program that uses Array.AsReadOnly
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
Then: A reference to the original array is stored as a field in ReadOnlyCollection. Little extra memory is used when this method is called.
IListThus: Array.AsReadOnly makes it possible to restrict access to arrays by client code.
But: This extra level of indirection has a performance cost. And it introduces a name change: the Length property becomes Count.