Home > Software design >  EnsureCapacity should not have if (newCapacity < min) newCapacity = min;
EnsureCapacity should not have if (newCapacity < min) newCapacity = min;

Time:09-18

I think if (newCapacity < min) newCapacity = min; should be removed, I have added items to the full capacity of the list but never hit breakpoint on line newCapacity = min;, Can someone tell the purpose of this line as well?

private void EnsureCapacity(int min) {
    if (_items.Length < min) {
        int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
        // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
        // Note that this check works even when _items.Length overflowed thanks to the (uint) cast
        if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
        if (newCapacity < min) newCapacity = min;
        Capacity = newCapacity;
    }
}

Here is the reference.

CodePudding user response:

Well, why should it be removed? Seems like this method set's this.Capacity to some number, which must not be less than min. And that is what it does. If newCapacity is less than the minimum specified, it's fixed.

CodePudding user response:

First of all, two remarks:

  • If you want to suggest changes or bug fixes for the .NET runtime, report them in their GitHub repo
  • You are looking at the old .NET Framework sources. Since .NET 6 EnsureCapacity is public, here is a more up-to-date version of it.

Can you give me an example where this condition if (newCapacity < min) will return true?

In .NET 6 and above you can easily come up with such an example: just call EnsureCapacity(100) on a newly created list.

As for the old .NET Framework code base with the private EnsureCapacity: InsertRange calls EnsureCapacity(_size count) when the collection to insert is an ICollection<T>. So to satisfy your condition you just need to call new List<int>().AddRange(new int[100]), for example.

  • Related