I am trying to limit the size of my generic list so that after it contains a certain amount of values, it won\'t add any more.
I am trying to do this using the Capac
There are several different ways to add things to a List: Add, AddRange, Insert, etc.
Consider a solution that inherits from Collection:
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
This way the capacity is respected whether you Add or Insert.