6

using ILspy the code is :

private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
    int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
    if (num > 2146435071)
    {
        num = 2146435071;
    }
    if (num < min)
    {
        num = min;
    }
    this.Capacity = num;
}
}

why is it checking if the num is greater than 2146435071 specifically shouldn't it just check for underflow & set num=Int.Max or anyother value greater than min?

M.U
  • 381
  • 3
  • 10
  • 1
    Note that if `_items.Length * 2` overflows (and the result becomes negative), `num` will later be changed to `min` because of the last `if`. It does seem a little strange that exceeding `0x7fefffff` without overflowing leads to another result than exceeding `0x7fffffff`, i.e. overflowing. – Jeppe Stig Nielsen Mar 09 '14 at 10:01
  • Well in the first if-statement `num` is casted to `uint` which ensures correct overflow checking. – AnorZaken Feb 01 '16 at 19:01

1 Answers1

5

This is connected to a fact, that List<T> uses array as internal storage, and maximum array size is set to 2146435071.

Read What is the maximum length of an array in .NET on 64-bit Windows about array max size.

You can easily create your own IList<T> implementation which will not use array as internal storage, and will allow more than 2146435071 elements. Of course, you're still limited by int.MaxValue as max number of elements, because IList<T>.Count returns int.

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 2
    That link also mentions that `2146435071` is `0x7fefffff` and yes, it seems the value was chosen to make sure the backing array can support it. – Jeppe Stig Nielsen Mar 09 '14 at 09:56