Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does c# List implementation specify this exact value in the ensure capacity method?

Tags:

c#

list

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?

like image 412
M.U Avatar asked Mar 09 '14 09:03

M.U


1 Answers

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.

like image 51
MarcinJuraszek Avatar answered Nov 17 '22 23:11

MarcinJuraszek