Reputation: 2103
Is Capacity property more useful in a List than in the other collections such as Stack and Queue? Or is there another way to get the capacity of a Stack or a Queue?
Upvotes: 15
Views: 5293
Reputation: 109732
I think that the reason that List
has a Capacity
property and Stack
and Queue
do not is that the normal usage of those types is different.
For a List
it is fairly common to populate it with a large set of values, even some time after it has been created. Providing the Capacity
property (and constructor argument) helps to mitigate the number of reallocations that would be done when adding a large number of items to the list.
Stack
and Queue
on the other hand do not tend to have large numbers of items added to them at once after they've been created.
Presumably Microsoft decided that it wasn't worth adding the Capacity
property because it wouldn't be used very much.
However, do note that Queue does have a constructor that allows you to specify an initial capacity, and so does Stack.
Also note that both classes also have a TrimExcess()
method, as mentioned by @drch below.
So Microsoft thought it would be useful at construction time, but not useful later on - so they only added the capacity functionality to the constructors.
(Incidentally I've just had a quick check through our code base, and it seems that the only time we use a capacity for List
is in fact at construction time. So maybe if Microsoft were designing List now, they might also omit the Capacity
property for List...)
Upvotes: 6
Reputation: 174369
This information is not exposed by Stack<T>
or Queue<T>
. This information isn't even stored explicitly in those classes, only implicitly in form of the length of the internal array.
Your only option to get that would be to use reflection to access the array and get it's length.
Upvotes: 2
Reputation: 44706
Stack
and Queue
are LIFO and FIFO structures respectively.
In both cases, you (as a consumer of the API) generally only need to know how to put data into the structure, and how to get data out again. You aren't concerned with the length of the data structure, only with push
and pop
.
If you need to get the capacity for any reason (a bounded stack/queue perhaps?) then it'd probably be better to hide that detail from the end user and implement your own stack/queue structure.
Upvotes: 3