limit list capacity

  • Thread starter Thread starter Tem
  • Start date Start date
I would like it to throw an exception saying the limit has been reached
 
Not with List<T>; however, it would be fairly trivial to inherit from
Collection<T> to enforce this:

public class BoundCollection<T> : Collection<T>
{
private readonly int maxCount;
public BoundCollection(int maxCount)
{
if (maxCount <= 0) throw new
ArgumentOutOfRangeException("maxCount");
this.maxCount = maxCount;
}
protected override void InsertItem(int index, T item)
{
if (Count >= maxCount)
{
throw new InvalidOperationException("No room");
}
base.InsertItem(index, item);
}
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top