Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the size of List(Of T) - VB.NET

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 Capacity property of the List object, but this does not seem to work.

        Dim slotDates As New List(Of Date)
        slotDates.Capacity = 7

How would people advice limiting the size of a list?

I am trying to avoid checking the size of the List after each object is added.

like image 886
w4ymo Avatar asked Mar 24 '09 13:03

w4ymo


1 Answers

There is no built-in way to limit the size of a List(Of T). The Capacity property is merely modifying the size of the underyling buffer, not restricting it.

If you want to limit the size of the List, you'll need to create a wrapper which checks for invalid size's. For example

Public Class RestrictedList(Of T)
  Private _list as New List(Of T)
  Private _limit as Integer
  Public Property Limit As Integer 
    Get 
      return _limit
    End Get
    Set 
      _limit = Value
    End Set
  End Property

  Public Sub Add(T value) 
    if _list.Count = _limit Then
      Throw New InvalidOperationException("List at limit")
    End If
    _list.Add(value)
  End Sub
End Class
like image 162
JaredPar Avatar answered Sep 29 '22 11:09

JaredPar