-3

I have a list that should be completely removed once every frame on an interactive app.

I reserved a capacity to 10.000 items at the beginning to avoid the overhead of adding items one by one.

Then I want to remove all of them. Apparently using Clear() will set Capacity to 0. Does it? How do I keep the capacity then?

Darkgaze
  • 2,280
  • 6
  • 36
  • 59
  • 2
    No, use [the source](https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,ca7bce81a50b0aeb) Luke. – Hans Passant May 22 '19 at 09:35
  • 2
    @HansPassant or RTFM - ["Capacity remains unchanged"](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.clear?view=netframework-4.8#remarks) – Marc Gravell May 22 '19 at 09:39

1 Answers1

2

Clear() does not reset the capacity:

var list = new List<int>(500);
list.Add(42);
list.Clear();
Console.WriteLine(list.Count); // 0
Console.WriteLine(list.Capacity); // 500

(at least, not on regular .NET Framework / .NET Core). So: just call Clear(). If you're using something more exotic, you'll need to be specific about your target framework.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks. I don't know why people downvoted my question. It could happen that I didn't know the sources were open. – Darkgaze May 24 '19 at 13:32