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.
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
You should implement your own list/collection if you need to restrict the maximum quantity of item in it.
List has no such facility.
The capacity stuff is just a performance optimisation.
You are going to have to roll your own class, derive off list and override the Add implementation.
You'll want to derive a new
LimitedList
and shadow the adding methods. Something like this will get you started.Just realised you're in VB, I'll translate shortly
Edit See Jared's for a VB version. I'll leave this here in case someone wants a C# version to get started with.
For what it's worth mine takes a slightly different approach as it extends the List class rather than encapsulating it. Which approach you want to use depends on your situation.
There are several different ways to add things to a
List<T>
: Add, AddRange, Insert, etc.Consider a solution that inherits from
Collection<T>
:This way the capacity is respected whether you
Add
orInsert
.