To make a List or Collection of class read-only in C# and VB.NET you can use the following snippet.

Sample C#

public class Test
{
	private readonly List<int> _testList = new List<int>();

	public IList<int> TestList 
	{
		get { return _testList.AsReadOnly(); }
	}

	public Test()
	{
		_testList.Add(0);
		_testList.Add(1);
		_testList.Add(2);
		_testList.Add(3);
		_testList.Add(4);
		_testList.Add(5);
	}
}

Sample VB.NET

Public Class Test
	Private ReadOnly _testList As New List(Of Integer)()

	Public ReadOnly Property TestList() As IList(Of Integer)
		Get
			Return _testList.AsReadOnly()
		End Get
	End Property

	Public Sub New()
		_testList.Add(0)
		_testList.Add(1)
		_testList.Add(2)
		_testList.Add(3)
		_testList.Add(4)
		_testList.Add(5)
	End Sub
End Class

One thought on “How to make a List or Collection of class read-only in C# and VB.NET”

Leave a Reply