There are several ways to add things to a List<T> : Add, AddRange, Insert, etc.
Consider a solution that inherits from Collection<T> :
Public Class LimitedCollection(Of T) Inherits System.Collections.ObjectModel.Collection(Of T) Private _Capacity As Integer Public Property Capacity() As Integer Get Return _Capacity End Get Set(ByVal value As Integer) _Capacity = value End Set End Property Protected Overrides Sub InsertItem(ByVal index As Integer, ByVal item As T) If Me.Count = Capacity Then Dim message As String = String.Format("List cannot hold more than {0} items", Capacity) Throw New InvalidOperationException(message) End If MyBase.InsertItem(index, item) End Sub End Class
Thus, the ability is respected regardless of whether you are Add or Insert .
Ryan lundy
source share