ArrayList in .NET: how do you get the current number of elements stored?

Difficulty: Easy

Correct Answer: arr.Count

Explanation:


Introduction / Context:
ArrayList is a resizable array in System.Collections. Knowing the difference between capacity and count is key for correct memory and performance management.



Given Data / Assumptions:

  • We are using System.Collections.ArrayList (non-generic).
  • We want the number of elements actually contained.


Concept / Approach:
ArrayList exposes two size-related members: Count and Capacity. Count returns how many elements are currently stored. Capacity is the size of the internal array (allocation) and may be greater than Count. Other listed members either do not exist or are not used for this purpose.



Step-by-Step Solution:

Use arr.Count → returns the number of elements present.arr.Capacity → internal storage size, not the active element count.arr.GrowSize / arr.MaxIndex / arr.UpperBound → not members of ArrayList for this purpose.


Verification / Alternative check:
Add items and inspect Count vs. Capacity in a debugger; Count increases by one per Add, Capacity grows in steps.



Why Other Options Are Wrong:
They either refer to non-existent members or to Capacity, which is distinct from count.



Common Pitfalls:
Using Capacity to loop can lead to null entries or index errors. Always iterate up to Count.



Final Answer:
arr.Count

More Questions from Collection Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion