List(Of T).AsReadOnly Method
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Returns a read-only IList(Of T) wrapper for the current collection.
Assembly: mscorlib (in mscorlib.dll)
Return Value
Type: System.Collections.ObjectModel.ReadOnlyCollection(Of T)A ReadOnlyCollection(Of T) that acts as a read-only wrapper around the current List(Of T).
To prevent any modifications to List(Of T), expose List(Of T) only through this wrapper.
A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.
This method is an O(1) operation.
The following code example demonstrates the AsReadOnly method. A List(Of T) of strings with a capacity of 4 is created, because the ultimate size of the list is known to be exactly 4. The list is populated with four strings, and the AsReadOnly method is used to get a read-only IList(Of T) generic interface implementation that wraps the original list.
An element of the original list is set to "Coelophysis" using the Item property (the indexer in C#), and the contents of the read-only list are displayed again to demonstrate that it is just a wrapper for the original list.
Imports System.Collections.Generic Public Class Example Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock) Dim dinosaurs As New List(Of String)(4) outputBlock.Text &= String.Format(vbLf & "Capacity: {0}", dinosaurs.Capacity) & vbCrLf dinosaurs.Add("Tyrannosaurus") dinosaurs.Add("Amargasaurus") dinosaurs.Add("Mamenchisaurus") dinosaurs.Add("Deinonychus") outputBlock.Text &= vbCrLf For Each dinosaur As String In dinosaurs outputBlock.Text &= dinosaur & vbCrLf Next outputBlock.Text &= vbLf & _ "Dim roDinosaurs As IList(Of String) = dinosaurs.AsReadOnly" & vbCrLf Dim roDinosaurs As IList(Of String) = dinosaurs.AsReadOnly outputBlock.Text &= vbLf & "Elements in the read-only IList:" & vbCrLf For Each dinosaur As String In roDinosaurs outputBlock.Text &= dinosaur & vbCrLf Next outputBlock.Text &= vbLf & "dinosaurs(2) = ""Coelophysis""" & vbCrLf dinosaurs(2) = "Coelophysis" outputBlock.Text &= vbLf & "Elements in the read-only IList:" & vbCrLf For Each dinosaur As String In roDinosaurs outputBlock.Text &= dinosaur & vbCrLf Next End Sub End Class ' This code example produces the following output: ' 'Capacity: 4 ' 'Tyrannosaurus 'Amargasaurus 'Mamenchisaurus 'Deinonychus ' 'Dim roDinosaurs As IList(Of String) = dinosaurs.AsReadOnly ' 'Elements in the read-only IList: 'Tyrannosaurus 'Amargasaurus 'Mamenchisaurus 'Deinonychus ' 'dinosaurs(2) = "Coelophysis" ' 'Elements in the read-only IList: 'Tyrannosaurus 'Amargasaurus 'Coelophysis 'Deinonychus